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 superrust-analyzer cargo roots 0.0.8 numerical/::superrust-analyzer cargo roots 0.0.8 crate/::FloatTyperust-analyzer cargo roots 0.0.8 float/FloatType#;
26 use superrust-analyzer cargo roots 0.0.8 numerical/::Convergencyrust-analyzer cargo roots 0.0.8 numerical/Convergency#;
27 use superrust-analyzer cargo roots 0.0.8 numerical/::SearchErrorrust-analyzer cargo roots 0.0.8 numerical/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_raphsonrust-analyzer cargo roots 0.0.8 numerical/newton_raphson/find_root_newton_raphson().<F, Func, Deriv>(
65 start: F,
66 mut f: Func,
67 mut d: Deriv,
68 convergency: &mut dyn Convergencyrust-analyzer cargo roots 0.0.8 numerical/Convergency#<F>,
69 ) -> Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<F, SearchErrorrust-analyzer cargo roots 0.0.8 numerical/SearchError#>
70 where
71 F: FloatTyperust-analyzer cargo roots 0.0.8 float/FloatType#,
72 Func: FnMutrust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/function/FnMut#(F) -> F,
73 Deriv: FnMutrust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/function/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_foundrust-analyzer cargo roots 0.0.8 numerical/Convergency#is_root_found().(f) {
82 return Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(x);
83 }
84 // Derivative is 0; try to correct the bad starting point
85 if convergency.is_root_foundrust-analyzer cargo roots 0.0.8 numerical/Convergency#is_root_found().(d) {
86 if iter rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[usize][`PartialEq<Self>`]eq().==rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[usize][`PartialEq<Self>`]eq(). rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[usize][`PartialEq<Self>`]eq().0 {
87 x = x rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/Add#add().+rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/Add#add(). rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/Add#add().F::onerust-analyzer cargo roots 0.0.8 float/FloatType#one().();
88 iter = iter rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[usize][`Add<Self>`]add().+rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[usize][`Add<Self>`]add(). rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[usize][`Add<Self>`]add().1;
89 continue;
90 } else {
91 return Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(SearchErrorrust-analyzer cargo roots 0.0.8 numerical/SearchError#::ZeroDerivativerust-analyzer cargo roots 0.0.8 numerical/SearchError#ZeroDerivative#);
92 }
93 }
94
95 let x1 = x rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/Sub#sub().-rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/Sub#sub(). rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/Sub#sub().f rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/Div#div()./rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/Div#div(). rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/Div#div().d;
96 if convergency.is_convergedrust-analyzer cargo roots 0.0.8 numerical/Convergency#is_converged().(x, x1) {
97 return Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(x1);
98 }
99
100 x = x1;
101 iter = iter rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[usize][`Add<Self>`]add().+rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[usize][`Add<Self>`]add(). rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[usize][`Add<Self>`]add().1;
102
103 if convergency.is_iteration_limit_reachedrust-analyzer cargo roots 0.0.8 numerical/Convergency#is_iteration_limit_reached().(iter) {
104 return Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(SearchErrorrust-analyzer cargo roots 0.0.8 numerical/SearchError#::NoConvergencyrust-analyzer cargo roots 0.0.8 numerical/SearchError#NoConvergency#);
105 }
106 }
107 }
108
109 #[cfg(test)]
110 mod testrust-analyzer cargo roots 0.0.8 numerical/newton_raphson/test/ {
111 use superrust-analyzer cargo roots 0.0.8 numerical/newton_raphson/::superrust-analyzer cargo roots 0.0.8 numerical/::*;
112 use superrust-analyzer cargo roots 0.0.8 numerical/newton_raphson/::*;
113
114 #[testrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/test:]
115 fn test_find_root_newton_raphsonrust-analyzer cargo roots 0.0.8 numerical/newton_raphson/test/test_find_root_newton_raphson().() {
116 let f = |x| 1f64 rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[f64][`Mul<Self>`]mul().*rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[f64][`Mul<Self>`]mul(). rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[f64][`Mul<Self>`]mul().x rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[f64][`Mul<Self>`]mul().*rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[f64][`Mul<Self>`]mul(). rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[f64][`Mul<Self>`]mul().x rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[f64][`Sub<Self>`]sub().-rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[f64][`Sub<Self>`]sub(). rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[f64][`Sub<Self>`]sub().1f64;
117 let d = |x| 2f64 rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[f64][`Mul<Self>`]mul().*rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[f64][`Mul<Self>`]mul(). rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[f64][`Mul<Self>`]mul().x;
118 let mut conv = debug_convergencyrust-analyzer cargo roots 0.0.8 numerical/debug_convergency/::DebugConvergencyrust-analyzer cargo roots 0.0.8 numerical/debug_convergency/DebugConvergency#::newrust-analyzer cargo roots 0.0.8 numerical/debug_convergency/impl#[`DebugConvergency<F>`]new().(1e-15f64, 30);
119
120 conv.resetrust-analyzer cargo roots 0.0.8 numerical/debug_convergency/impl#[`DebugConvergency<F>`]reset().();
121 assert_float_eqrust-analyzer cargo roots 0.0.8 assert_float_eq!!(
122 1e-15f64,
123 find_root_newton_raphsonrust-analyzer cargo roots 0.0.8 numerical/newton_raphson/find_root_newton_raphson().(10f64, &f, &d, &mut conv).okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]ok().().unwraprust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/impl#[`Option<T>`]unwrap().(),
124 1f64
125 );
126 assert_eqrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/assert_eq!!(8, conv.get_iter_countrust-analyzer cargo roots 0.0.8 numerical/debug_convergency/impl#[`DebugConvergency<F>`]get_iter_count().());
127
128 conv.resetrust-analyzer cargo roots 0.0.8 numerical/debug_convergency/impl#[`DebugConvergency<F>`]reset().();
129 assert_float_eqrust-analyzer cargo roots 0.0.8 assert_float_eq!!(
130 1e-15f64,
131 find_root_newton_raphsonrust-analyzer cargo roots 0.0.8 numerical/newton_raphson/find_root_newton_raphson().(-rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[f64][Neg]neg().10f64, &f, &d, &mut conv).okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]ok().().unwraprust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/impl#[`Option<T>`]unwrap().(),
132 -rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/arith/impl#[f64][Neg]neg().1f64
133 );
134 assert_eqrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/assert_eq!!(8, conv.get_iter_countrust-analyzer cargo roots 0.0.8 numerical/debug_convergency/impl#[`DebugConvergency<F>`]get_iter_count().());
135 }
136 }