Newton’s Method implemented in Rust.

applied.math.coding
4 min readOct 13, 2022

In this short story I want to provide a Rust implementation of Newton’s method for finding roots of functions. Newton’s method can be generalized to some extend but for real valued functions with one argument it looks like so:

Let f be a real-valued function f on some interval and f' denote its derivative. Then the following iteration is the Newton schema:

x_{n+1} = x_n - f(x_n) / f'(x_{n})

This sequence under certain conditions can be shown to converge against a root r of f, that is, f(r) = 0. One of the main criteria that ensures convergence is to have chosen x_0 close enough to r. More details about the theory behind this method can be found here.

Let us focus now on the implementation in Rust. Although, to just implement the iteration is straightforward, we will see the Rust provides some nice features to have it applicable as general as possible.

For everyone who needs a wrap-up in Rust, be invited to this little introduction.

Implementation:

In essence, we provide to the method two borrowed references, one to f and the other to its derivative. Note, what we are doing with the generic type T. In principle we just could write this function to work for the type f64 or f32, but in order to leave this open we use T. In many other languages we know would restrict the type T by some bounds to ensure it is numeric. In Rust we can do better! Instead of requiring T to be numeric, we require it implements the operator Div (division) and Sub (subtraction). This is fantastic in so far that our T must not necessarily be f64 or f32. For instance, it could be the type c that is used in this crate to represent complex numbers. This even would make sense because it can be shown the Newton…

--

--

applied.math.coding

I am a Software Developer - Java, Rust, SQL, TypeScript - with strong interest doing research in pure and applied Mathematics.