Debian Codegraph @

src/numerical/secant.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 secant method.
30 ///
31 /// Pro
32 ///
33 /// + Simple
34 /// + No need for initial bracketing
35 /// + No need for derivative function
36 ///
37 /// Contra
38 ///
39 /// - Impossible to predict which root will be found when many roots exist
40 /// - Unstable convergency for non-trivial functions
41 /// - Cannot continue when two consecutive iterations have the same value
42 ///
43 /// # Failures
44 /// ## ZeroDerivative
45 /// Two consecutive points have the same value. Algorithm cannot continue.
46 /// ## NoConvergency
47 /// Algorithm cannot find a root within the given number of iterations.
48 /// # Examples
49 ///
50 /// ```
51 /// use roots::SimpleConvergency;
52 /// use roots::find_root_secant;
53 ///
54 /// let f = |x| { 1f64*x*x - 1f64 };
55 /// let mut convergency = SimpleConvergency { eps:1e-15f64, max_iter:30 };
56 ///
57 /// let root1 = find_root_secant(10f64, 0f64, &f, &mut convergency);
58 /// // Returns approximately Ok(1);
59 ///
60 /// let root2 = find_root_secant(-10f64, 0f64, &f, &mut 1e-15f64);
61 /// // Returns approximately Ok(-1);
62 /// ```
63 pub fn find_root_secant<F, Func>(first: F, second: F, mut f: Func, convergency: &mut dyn Convergency<F>) -> Result<F, SearchError>
64 where
65 F: FloatType,
66 Func: FnMut(F) -> F,
67 {
68 let mut x1 = first;
69 let mut y1 = f(x1);
70 if convergency.is_root_found(y1) {
71 return Ok(x1);
72 }
73 let mut x2 = second;
74 let mut y2 = f(x2);
75 if convergency.is_root_found(y2) {
76 return Ok(x2);
77 }
78
79 let mut iter = 0;
80 loop {
81 if convergency.is_root_found(y1 - y2) {
82 return Err(SearchError::ZeroDerivative);
83 }
84 let x = x2 - y2 * (x2 - x1) / (y2 - y1);
85 if convergency.is_converged(x, x2) {
86 return Ok(x);
87 }
88 let y = f(x);
89 if convergency.is_root_found(y) {
90 return Ok(x);
91 }
92
93 x1 = x2;
94 y1 = y2;
95 x2 = x;
96 y2 = y;
97
98 iter = iter + 1;
99 if convergency.is_iteration_limit_reached(iter) {
100 return Err(SearchError::NoConvergency);
101 }
102 }
103 }
104
105 #[cfg(test)]
106 mod test {
107 use super::super::*;
108 use super::*;
109
110 #[test]
111 fn test_find_root_secant() {
112 let f = |x| 1f64 * x * x - 1f64;
113 let mut conv = debug_convergency::DebugConvergency::new(1e-15f64, 30);
114
115 conv.reset();
116 assert_float_eq!(1e-15f64, find_root_secant(10f64, 0f64, &f, &mut conv).ok().unwrap(), 1f64);
117 assert_eq!(12, conv.get_iter_count());
118
119 conv.reset();
120 assert_float_eq!(1e-15f64, find_root_secant(-10f64, 0f64, &f, &mut conv).ok().unwrap(), -1f64);
121 assert_eq!(12, conv.get_iter_count());
122
123 conv.reset();
124 assert_eq!(
125 find_root_secant(10f64, -10f64, &f, &mut conv),
126 Err(SearchError::ZeroDerivative)
127 );
128 assert_eq!(0, conv.get_iter_count());
129 }
130 }