Mon, 31 Mar 2025 13:33:14 -0500
README typofix
| 37 | 1 | /*! |
| 2 | Newton method in 2D. | |
| 3 | */ | |
| 4 | ||
| 5 | use alg_tools::types::*; | |
| 6 | ||
| 46 | 7 | /// Approximately solves $f(x)=b$ using Newton's method in 1D. |
| 8 | /// | |
| 9 | /// The function `g` should return $(f'(x), f(x))$. | |
| 10 | /// The initial iterate will be `x`, and exactly `iters` iterations are taken. | |
| 37 | 11 | #[inline] |
| 12 | pub fn newton_sym1x1<F : Float>( | |
| 13 | g : impl Fn(F) -> (F, F), | |
| 14 | mut x : F, | |
| 15 | iters : usize | |
| 16 | ) -> F { | |
| 17 | for _i in 0..iters { | |
| 18 | let (a, b) = g(x); | |
| 19 | x -= b / a | |
| 20 | } | |
| 21 | x | |
| 22 | } | |
| 23 | ||
| 46 | 24 | /// Approximately solves $f(x)=b$ using Newton's method in "D. |
| 25 | /// | |
| 26 | /// The function `g` should return $(∇f(x), f(x))$. | |
| 27 | /// The Hessian $A=∇f(x)$ should be symmetric and given in the form $[A_{11}, A_{12}, A_{22}]$. | |
| 28 | /// The initial iterate will be `[x1, x2]`, and exactly `iters` iterations are taken. | |
| 37 | 29 | #[inline] |
| 30 | pub fn newton_sym2x2<F : Float>( | |
| 31 | g : impl Fn(F, F) -> ([F; 3], [F; 2]), | |
| 32 | [mut x1, mut x2] : [F; 2], | |
| 33 | iters : usize | |
| 34 | ) -> [F; 2] { | |
| 35 | for _i in 0..iters { | |
| 36 | let ([a11, a12, a22], [b1, b2]) = g(x1, x2); | |
| 37 | let q = a11 * a22 - a12 * a12; | |
| 38 | x1 -= (a22 * b1 - a12 * b2) / q; | |
| 39 | x2 -= (a11 * b2 - a12 * b1) / q; | |
| 40 | } | |
| 41 | [x1, x2] | |
| 42 | } | |
| 43 |