newton_raphson/
lib.rs

1//! A minimal module for calculating roots using the Newton-Raphson method,
2//! as described by [Wikipedia](https://en.wikipedia.org/wiki/Newton's_method)
3//!
4//! # Examples
5//!
6//! [Solution of cos(c) = x^3^]
7//! (https://en.wikipedia.org/wiki/Newton%27s_method#Solution_of_cos.28x.29_.3D_x3)
8//!
9//! ```
10//! use std::f64;
11//! use newton_raphson::find_root;
12//! fn cosx(x: f64) -> f64 {
13//!     x.cos() - (x * x * x)
14//! }
15//!
16//! fn cosx_d(x: f64) -> f64 {
17//!     -x.sin() - 3.0 * (x * x)
18//! }
19//!
20//! assert_eq!(0.8654740331016144, find_root(cosx, cosx_d, 0.5, 6));
21//! ```
22
23/// Finds the root of the function f
24///
25/// # Examples
26///
27/// [Finding the square root of a number]
28/// (https://en.wikipedia.org/wiki/Newton%27s_method#Square_root_of_a_number)
29///
30/// ```
31/// use newton_raphson::find_root;
32/// fn sqrt_of_612(x: f64) -> f64 {
33///     (x * x) - 612.0
34/// }
35///
36/// fn sqrt_of_612_d(x: f64) -> f64 {
37///     2.0 * x
38/// }
39///
40/// assert_eq!(24.738633753766084, find_root(sqrt_of_612, sqrt_of_612_d, 10.0, 5))
41/// ```
42pub fn find_root(f: fn(f64) -> f64, fd: fn(f64) -> f64, guess: f64, iterations: i32) -> f64 {
43    let mut result = guess;
44    for _ in 0..iterations {
45        result = iteration(f, fd, result);
46    }
47    result
48}
49
50/// Runs through one iteration of the Newton-Raphson method
51///
52/// # Examples
53///
54/// [Finding the square root of a number]
55/// (https://en.wikipedia.org/wiki/Newton%27s_method#Square_root_of_a_number)
56///
57/// ```
58/// use newton_raphson::iteration;
59/// fn sqrt_of_612(x: f64) -> f64 {
60///     (x * x) - 612.0
61/// }
62///
63/// fn sqrt_of_612_d(x: f64) -> f64 {
64///     2.0 * x
65/// }
66///
67/// assert_eq!(35.6, iteration(sqrt_of_612, sqrt_of_612_d, 10.0));
68/// ```
69pub fn iteration(f: fn(f64) -> f64, fd: fn(f64) -> f64, guess: f64) -> f64 {
70    guess - f(guess) / fd(guess)
71}