Debian Codegraph @

src/numerical/newton_raphson.rs

raw symbols SCIP
1 // Copyright (c) 2015, Mikhail Vorotilov
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are met:
6 //
7 // * Redistributions of source code must retain the above copyright notice, this
8 // list of conditions and the following disclaimer.
9 //
10 // * Redistributions in binary form must reproduce the above copyright notice,
11 // this list of conditions and the following disclaimer in the documentation
12 // and/or other materials provided with the distribution.
13 //
14 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
15 // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17 // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
18 // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
20 // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
21 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
22 // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24
25 use super::super::FloatType;
26 use super::Convergency;
27 use super::SearchError;
28
29 /// Find a root of the function f(x) = 0 using the Newton-Raphson method.
30 ///
31 /// Pro
32 ///
33 /// + Simple
34 /// + Fast convergency for well-behaved functions
35 /// + No need for initial bracketing
36 ///
37 /// Contra
38 ///
39 /// - Needs derivative function
40 /// - Impossible to predict which root will be found when many roots exist
41 /// - Unstable convergency for non-trivial functions
42 /// - Cannot continue when derivative is zero
43 ///
44 /// # Failures
45 /// ## ZeroDerivative
46 /// The stationary point of the function is encountered. Algorithm cannot continue.
47 /// ## NoConvergency
48 /// Algorithm cannot find a root within the given number of iterations.
49 /// # Examples
50 /// ```
51 /// use roots::SimpleConvergency;
52 /// use roots::find_root_newton_raphson;
53 ///
54 /// let f = |x| { 1f64*x*x - 1f64 };
55 /// let d = |x| { 2f64*x };
56 /// let mut convergency = SimpleConvergency { eps:1e-15f64, max_iter:30 };
57 ///
58 /// let root1 = find_root_newton_raphson(10f64, &f, &d, &mut convergency);
59 /// // Returns approximately Ok(1);
60 ///
61 /// let root2 = find_root_newton_raphson(-10f64, &f, &d, &mut 1e-15f64);
62 /// // Returns approximately Ok(-1);
63 /// ```
64 pub fn find_root_newton_raphson<F, Func, Deriv>(
65 start: F,
66 mut f: Func,
67 mut d: Deriv,
68 convergency: &mut dyn Convergency<F>,
69 ) -> Result<F, SearchError>
70 where
71 F: FloatType,
72 Func: FnMut(F) -> F,
73 Deriv: FnMut(F) -> F,
74 {
75 let mut x = start;
76
77 let mut iter = 0;
78 loop {
79 let f = f(x);
80 let d = d(x);
81 if convergency.is_root_found(f) {
82 return Ok(x);
83 }
84 // Derivative is 0; try to correct the bad starting point
85 if convergency.is_root_found(d) {
86 if iter == 0 {
87 x = x + F::one();
88 iter = iter + 1;
89 continue;
90 } else {
91 return Err(SearchError::ZeroDerivative);
92 }
93 }
94
95 let x1 = x - f / d;
96 if convergency.is_converged(x, x1) {
97 return Ok(x1);
98 }
99
100 x = x1;
101 iter = iter + 1;
102
103 if convergency.is_iteration_limit_reached(iter) {
104 return Err(SearchError::NoConvergency);
105 }
106 }
107 }
108
109 #[cfg(test)]
110 mod test {
111 use super::super::*;
112 use super::*;
113
114 #[test]
115 fn test_find_root_newton_raphson() {
116 let f = |x| 1f64 * x * x - 1f64;
117 let d = |x| 2f64 * x;
118 let mut conv = debug_convergency::DebugConvergency::new(1e-15f64, 30);
119
120 conv.reset();
121 assert_float_eq!(
122 1e-15f64,
123 find_root_newton_raphson(10f64, &f, &d, &mut conv).ok().unwrap(),
124 1f64
125 );
126 assert_eq!(8, conv.get_iter_count());
127
128 conv.reset();
129 assert_float_eq!(
130 1e-15f64,
131 find_root_newton_raphson(-10f64, &f, &d, &mut conv).ok().unwrap(),
132 -1f64
133 );
134 assert_eq!(8, conv.get_iter_count());
135 }
136 }