| 1 | // Copyright (c) 2019, 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::find_roots_quadratic; |
| 26 | use super::super::FloatType; |
| 27 | use super::Convergency; |
| 28 | use super::Interval; |
| 29 | use super::Sample; |
| 30 | use super::SearchError; |
| 31 | |
| 32 | /// Definition of the quadratic equation a*x^2 + b*x + c |
| 33 | #[derive(Debug, PartialEq)] |
| 34 | pub struct Parabola<F> |
| 35 | where |
| 36 | F: FloatType, |
| 37 | { |
| 38 | a: F, |
| 39 | b: F, |
| 40 | c: F, |
| 41 | } |
| 42 | |
| 43 | impl<F> Parabola<F> |
| 44 | where |
| 45 | F: FloatType, |
| 46 | { |
| 47 | /// Restore coefficients of the quadratic equation by 3 points |
| 48 | fn from_three_points(p1: &Sample<F>, p2: &Sample<F>, p3: &Sample<F>) -> Self { |
| 49 | let denom = (p1.x - p2.x) * (p1.x - p3.x) * (p2.x - p3.x); |
| 50 | let a = (p3.x * (p2.y - p1.y) + p2.x * (p1.y - p3.y) + p1.x * (p3.y - p2.y)) / denom; |
| 51 | let b = (p1.x * p1.x * (p2.y - p3.y) + p3.x * p3.x * (p1.y - p2.y) + p2.x * p2.x * (p3.y - p1.y)) / denom; |
| 52 | let c = (p2.x * p2.x * (p3.x * p1.y - p1.x * p3.y) |
| 53 | + p2.x * (p1.x * p1.x * p3.y - p3.x * p3.x * p1.y) |
| 54 | + p1.x * p3.x * (p3.x - p1.x) * p2.y) |
| 55 | / denom; |
| 56 | |
| 57 | Parabola { a: a, b: b, c: c } |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | /// Find a root of the function f(x) = 0 using inverse quadratic approximation. |
| 62 | /// |
| 63 | /// Pro |
| 64 | /// |
| 65 | /// + Faster than linear approximation |
| 66 | /// + No need for derivative function |
| 67 | /// |
| 68 | /// Contra |
| 69 | /// |
| 70 | /// - sqrt is calculated on every step |
| 71 | /// - only works for polynomial-like functions |
| 72 | /// |
| 73 | /// # Failures |
| 74 | /// ## NoBracketing |
| 75 | /// Initial values do not bracket the root. |
| 76 | /// ## NoConvergency |
| 77 | /// Algorithm cannot find a root within the given number of iterations. |
| 78 | /// # Examples |
| 79 | /// |
| 80 | /// ``` |
| 81 | /// use roots::SimpleConvergency; |
| 82 | /// use roots::find_root_inverse_quadratic; |
| 83 | /// |
| 84 | /// let f = |x| { 1f64*x*x - 1f64 }; |
| 85 | /// let mut convergency = SimpleConvergency { eps:1e-15f64, max_iter:30 }; |
| 86 | /// |
| 87 | /// let root1 = find_root_inverse_quadratic(10f64, 0f64, &f, &mut convergency); |
| 88 | /// // Returns approximately Ok(1); |
| 89 | /// |
| 90 | /// let root2 = find_root_inverse_quadratic(-10f64, 0f64, &f, &mut 1e-15f64); |
| 91 | /// // Returns approximately Ok(-1); |
| 92 | /// ``` |
| 93 | pub fn find_root_inverse_quadratic<F, Func>(a: F, b: F, mut f: Func, convergency: &mut dyn Convergency<F>) -> Result<F, SearchError> |
| 94 | where |
| 95 | F: FloatType, |
| 96 | Func: FnMut(F) -> F, |
| 97 | { |
| 98 | let (x1, x2) = if a > b { (b, a) } else { (a, b) }; |
| 99 | let sample1 = Sample { x: x1, y: f(x1) }; |
| 100 | if convergency.is_root_found(sample1.y) { |
| 101 | return Ok(sample1.x); |
| 102 | } |
| 103 | let sample2 = Sample { x: x2, y: f(x2) }; |
| 104 | if convergency.is_root_found(sample2.y) { |
| 105 | return Ok(sample2.x); |
| 106 | } |
| 107 | if !sample1.is_bracketed_with(&sample2) { |
| 108 | return Err(SearchError::NoBracketing); |
| 109 | } |
| 110 | |
| 111 | // Initially, find x3 using the regula falsi method |
| 112 | let mut interval = Interval { |
| 113 | begin: sample1, |
| 114 | end: sample2, |
| 115 | }; |
| 116 | let mut x3 = interval.middle(); |
| 117 | if interval.is_converged(convergency) { |
| 118 | return Ok(x3); |
| 119 | } |
| 120 | let mut sample3 = Sample { x: x3, y: f(x3) }; |
| 121 | if convergency.is_root_found(sample3.y) { |
| 122 | return Ok(sample3.x); |
| 123 | } |
| 124 | |
| 125 | // Iterate quadratically |
| 126 | let mut iter = 0; |
| 127 | loop { |
| 128 | let parabola = Parabola::from_three_points(&interval.begin, &interval.end, &sample3); |
| 129 | |
| 130 | // Find the new approximation quadratically |
| 131 | x3 = if let Some(root) = find_roots_quadratic(parabola.a, parabola.b, parabola.c) |
| 132 | .as_ref() |
| 133 | .iter() |
| 134 | .find(|x| interval.contains_x(x)) |
| 135 | { |
| 136 | *root |
| 137 | } else { |
| 138 | // no roots inside interval, fallback to linear approximation |
| 139 | interval.middle() |
| 140 | }; |
| 141 | |
| 142 | // calculate the approximated value |
| 143 | sample3 = Sample { x: x3, y: f(x3) }; |
| 144 | |
| 145 | if convergency.is_root_found(sample3.y) { |
| 146 | return Ok(sample3.x); |
| 147 | } |
| 148 | |
| 149 | // Narrow down the search interval while keeping the root bracketed |
| 150 | if sample3.is_bracketed_with(&interval.begin) { |
| 151 | interval.end = Sample { |
| 152 | x: sample3.x, |
| 153 | y: sample3.y, |
| 154 | }; |
| 155 | } else { |
| 156 | interval.begin = Sample { |
| 157 | x: sample3.x, |
| 158 | y: sample3.y, |
| 159 | }; |
| 160 | } |
| 161 | |
| 162 | if interval.is_converged(convergency) { |
| 163 | return Ok(interval.middle()); |
| 164 | } |
| 165 | |
| 166 | iter = iter + 1; |
| 167 | if convergency.is_iteration_limit_reached(iter) { |
| 168 | return Err(SearchError::NoConvergency); |
| 169 | } |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | #[cfg(test)] |
| 174 | mod test { |
| 175 | use super::super::*; |
| 176 | use super::*; |
| 177 | |
| 178 | #[test] |
| 179 | fn test_find_root_inverse_quadratic() { |
| 180 | let f = |x| 1f64 * x * x - 1f64; |
| 181 | let mut conv = debug_convergency::DebugConvergency::new(1e-15f64, 30); |
| 182 | |
| 183 | conv.reset(); |
| 184 | assert_float_eq!( |
| 185 | 1e-15f64, |
| 186 | find_root_inverse_quadratic(10f64, 0f64, &f, &mut conv).ok().unwrap(), |
| 187 | 1f64 |
| 188 | ); |
| 189 | assert_eq!(0, conv.get_iter_count()); |
| 190 | |
| 191 | conv.reset(); |
| 192 | assert_float_eq!( |
| 193 | 1e-15f64, |
| 194 | find_root_inverse_quadratic(-10f64, 0f64, &f, &mut conv).ok().unwrap(), |
| 195 | -1f64 |
| 196 | ); |
| 197 | assert_eq!(0, conv.get_iter_count()); |
| 198 | |
| 199 | conv.reset(); |
| 200 | assert_eq!( |
| 201 | find_root_inverse_quadratic(10f64, 20f64, &f, &mut conv), |
| 202 | Err(SearchError::NoBracketing) |
| 203 | ); |
| 204 | let result = find_root_inverse_quadratic(10f64, 20f64, &f, &mut conv); |
| 205 | assert_eq!(result.unwrap_err().to_string(), "Bracketing Error"); |
| 206 | assert_eq!(0, conv.get_iter_count()); |
| 207 | } |
| 208 | |
| 209 | #[test] |
| 210 | fn test_from_three_points() { |
| 211 | assert_eq!( |
| 212 | Parabola { |
| 213 | a: 1f64, |
| 214 | b: 0f64, |
| 215 | c: -1f64 |
| 216 | }, |
| 217 | Parabola::from_three_points( |
| 218 | &Sample { x: -10f64, y: 99f64 }, |
| 219 | &Sample { x: -2f64, y: 3f64 }, |
| 220 | &Sample { x: 0f64, y: -1f64 } |
| 221 | ) |
| 222 | ); |
| 223 | assert_eq!( |
| 224 | Parabola { |
| 225 | a: 1f64, |
| 226 | b: 0f64, |
| 227 | c: -1f64 |
| 228 | }, |
| 229 | Parabola::from_three_points( |
| 230 | &Sample { x: 10f64, y: 99f64 }, |
| 231 | &Sample { x: 2f64, y: 3f64 }, |
| 232 | &Sample { x: 0f64, y: -1f64 } |
| 233 | ) |
| 234 | ); |
| 235 | assert_eq!( |
| 236 | Parabola { |
| 237 | a: 1f64, |
| 238 | b: 0f64, |
| 239 | c: -1f64 |
| 240 | }, |
| 241 | Parabola::from_three_points( |
| 242 | &Sample { x: -3f64, y: 8f64 }, |
| 243 | &Sample { x: 2f64, y: 3f64 }, |
| 244 | &Sample { x: 0f64, y: -1f64 } |
| 245 | ) |
| 246 | ); |
| 247 | } |
| 248 | } |