1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
/* This file is part of bacon.
 * Copyright (c) Wyatt Campbell.
 *
 * See repository LICENSE for information.
 */

use alga::general::{ComplexField, RealField};
use nalgebra::DVector;

mod polynomial;
pub use polynomial::*;

/// Use the bisection method to solve for a zero of an equation.
///
/// This function takes an interval and uses a binary search to find
/// where in that interval a function has a root. The signs of the function
/// at each end of the interval must be different
///
/// # Returns
/// Ok(root) when a root has been found, Err on failure
///
/// # Params
/// `(left, right)` The starting interval. f(left) * f(right) > 0.0
///
/// `f` The function to find the root for
///
/// `tol` The tolerance of the relative error between iterations.
///
/// `n_max` The maximum number of iterations to use.
///
/// # Examples
/// ```
/// use nalgebra::DVector;
/// use bacon_sci::roots::bisection;
///
/// fn cubic(x: f64) -> f64 {
///   x*x*x
/// }
/// //...
/// fn example() {
///   let solution = bisection((-1.0, 1.0), cubic, 0.001, 1000).unwrap();
/// }
/// ```
pub fn bisection<N: RealField>(
    (mut left, mut right): (N, N),
    f: fn(N) -> N,
    tol: N,
    n_max: usize,
) -> Result<N, String> {
    if left >= right {
        return Err("Bisection: requirement: right > left".to_owned());
    }

    let mut n = 1;

    let mut f_a = f(left);
    if (f_a * f(right)).is_sign_positive() {
        return Err("Bisection: requirement: Signs must be different".to_owned());
    }

    let mut half_interval = (left - right) * N::from_f64(0.5).unwrap();
    let mut middle = left + half_interval;

    if middle.abs() <= tol {
        return Ok(middle);
    }

    while n <= n_max {
        let f_p = f(middle);
        if (f_p * f_a).is_sign_positive() {
            left = middle;
            f_a = f_p;
        } else {
            right = middle;
        }

        half_interval = (right - left) * N::from_f64(0.5).unwrap();

        let middle_new = left + half_interval;

        if (middle - middle_new).abs() / middle.abs() < tol || middle_new.abs() < tol {
            return Ok(middle_new);
        }

        middle = middle_new;
        n += 1;
    }

    Err("Bisection: Maximum iterations exceeded".to_owned())
}

/// Use steffenson's method to find a fixed point
///
/// Use steffenson's method to find a value x so that f(x) = x, given
/// a starting point.
///
/// # Returns
/// `Ok(x)` so that `f(x) - x < tol` on success, `Err` on failure
///
/// # Params
/// `initial` inital guess for the fixed point
///
/// `f` Function to find the fixed point of
///
/// `tol` Tolerance from 0 to try and achieve
///
/// `n_max` maximum number of iterations
///
/// # Examples
/// ```
/// use bacon_sci::roots::steffensen;
/// fn cosine(x: f64) -> f64 {
///   x.cos()
/// }
/// //...
/// fn example() -> Result<(), String> {
///   let solution = steffensen(0.5f64, cosine, 0.0001, 1000)?;
///   Ok(())
/// }
pub fn steffensen<N: RealField + From<f64> + Copy>(
    mut initial: N,
    f: fn(N) -> N,
    tol: N,
    n_max: usize,
) -> Result<N, String> {
    let mut n = 0;

    while n < n_max {
        let guess = f(initial);
        let new_guess = f(guess);
        let diff =
            initial - (guess - initial).powi(2) / (new_guess - N::from(2.0) * guess + initial);
        if (diff - initial).abs() <= tol {
            return Ok(diff);
        }
        initial = diff;
        n += 1;
    }

    Err("Steffensen: Maximum number of iterations exceeded".to_owned())
}

/// Use Newton's method to find a root of a vector function.
///
/// Using a vector function and its derivative, find a root based on an initial guess
/// using Newton's method.
///
/// # Returns
/// `Ok(vec)` on success, where `vec` is a vector input for which the function is
/// zero. `Err` on failure.
///
/// # Params
/// `initial` Initial guess of the root. Should be near actual root. Slice since this
/// function finds roots of vector functions.
///
/// `f` Vector function for which to find the root
///
/// `f_deriv` Derivative of `f`
///
/// `tol` tolerance for error between iterations of Newton's method
///
/// `n_max` Maximum number of iterations
///
/// # Examples
/// ```
/// use nalgebra::DVector;
/// use bacon_sci::roots::newton;
/// fn cubic(x: &[f64]) -> DVector<f64> {
///   DVector::from_iterator(x.len(), x.iter().map(|x| x.powi(3)))
/// }
///
/// fn cubic_deriv(x: &[f64]) -> DVector<f64> {
///   DVector::from_iterator(x.len(), x.iter().map(|x| 3.0*x.powi(2)))
/// }
/// //...
/// fn example() {
///   let solution = newton(&[0.1], cubic, cubic_deriv, 0.001, 1000).unwrap();
/// }
/// ```
pub fn newton<N: ComplexField>(
    initial: &[N],
    f: fn(&[N]) -> DVector<N>,
    f_deriv: fn(&[N]) -> DVector<N>,
    tol: <N as ComplexField>::RealField,
    n_max: usize,
) -> Result<DVector<N>, String> {
    let mut guess = DVector::from_column_slice(initial);
    let mut norm = guess.dot(&guess).sqrt().abs();
    let mut n = 0;

    if norm <= tol {
        return Ok(guess);
    }

    while n < n_max {
        let f_val = f(guess.column(0).as_slice());
        let f_deriv_val = f_deriv(guess.column(0).as_slice());
        let adjustment = DVector::from_iterator(
            guess.column(0).len(),
            f_val
                .column(0)
                .iter()
                .zip(f_deriv_val.column(0).iter())
                .map(|(f, f_d)| *f / *f_d),
        );
        let new_guess = &guess - adjustment;
        let new_norm = new_guess.dot(&new_guess).sqrt().abs();
        if ((norm - new_norm) / norm).abs() <= tol || new_norm <= tol {
            return Ok(new_guess);
        }

        norm = new_norm;
        guess = new_guess;
        n += 1;
    }

    Err("Newton: Maximum iterations exceeded".to_owned())
}

/// Use secant method to find a root of a vector function.
///
/// Using a vector function and its derivative, find a root based on two initial guesses
/// using secant method.
///
/// # Returns
/// `Ok(vec)` on success, where `vec` is a vector input for which the function is
/// zero. `Err` on failure.
///
/// # Params
/// `initial` Initial guesses of the root. Should be near actual root. Slice since this
/// function finds roots of vector functions.
///
/// `f` Vector function for which to find the root
///
/// `tol` tolerance for error between iterations of Newton's method
///
/// `n_max` Maximum number of iterations
///
/// # Examples
/// ```
/// use nalgebra::DVector;
/// use bacon_sci::roots::secant;
/// fn cubic(x: &[f64]) -> DVector<f64> {
///   DVector::from_iterator(x.len(), x.iter().map(|x| x.powi(3)))
/// }
/// //...
/// fn example() {
///   let solution = secant((&[0.1], &[-0.1]), cubic, 0.001, 1000).unwrap();
/// }
/// ```
pub fn secant<N: ComplexField>(
    initial: (&[N], &[N]),
    f: fn(&[N]) -> DVector<N>,
    tol: <N as ComplexField>::RealField,
    n_max: usize,
) -> Result<DVector<N>, String> {
    let mut n = 0;

    let mut left = DVector::from_column_slice(initial.0);
    let mut right = DVector::from_column_slice(initial.1);

    let mut left_val = f(initial.0);
    let mut right_val = f(initial.1);

    let mut norm = right.dot(&right).sqrt().abs();
    if norm <= tol {
        return Ok(right);
    }

    while n <= n_max {
        let adjustment = DVector::from_iterator(
            right_val.iter().len(),
            right_val.iter().enumerate().map(|(i, q)| {
                *q * (*right.get(i).unwrap() - *left.get(i).unwrap())
                    / (*q - *left_val.get(i).unwrap())
            }),
        );
        let new_guess = &right - adjustment;
        let new_norm = new_guess.dot(&new_guess).sqrt().abs();
        if ((norm - new_norm) / norm).abs() <= tol || new_norm <= tol {
            return Ok(new_guess);
        }

        norm = new_norm;
        left_val = right_val;
        left = right;
        right = new_guess;
        right_val = f(right.column(0).as_slice());
        n += 1;
    }

    Err("Secant: Maximum iterations exceeded".to_owned())
}

/*
pub fn muller<N: ComplexField+From<f64>+Into<N>>(
  initial: (N, N, N),
  f: fn(N) -> N,
  tol: <N as ComplexField>::RealField,
  n_max: usize
) -> Result<N, String> {
  let mut n = 0;

  let mut poly_0 = initial.0;
  let mut poly_1 = initial.1;
  let mut poly_2 = initial.2;

  let mut h_1 = poly_1 - poly_0;
  let mut h_2 = poly_2 - poly_1;
  let mut f_at_1 = f(poly_1);
  let mut f_at_2 = f(poly_2);
  let mut delta_1 = (f_at_1 - f(poly_0)) / h_2;
  let mut delta_2 = (f_at_2 - f_at_1) / h_2;
  let mut d = (delta_2 - delta_1) / (h_2 + h_1);

  while n < n_max {
    let b = delta_2 + h_2*d;
    let determinant = (b.powi(2) - N::from(4.0)*f_at_2*d).sqrt();
    let error = if (b - determinant).abs() < (b + determinant).abs() { b + determinant } else { b - determinant };
    let h = N::from(-2.0) * f_at_2 / error;
    let p = poly_2 + h;

    if h.abs() <= tol {
      return Ok(p);
    }

    poly_0 = poly_1;
    poly_1 = poly_2;
    poly_2 = p;
    f_at_1 = f(poly_1);
    f_at_2 = f(poly_2);
    h_1 = poly_1 - poly_2;
    h_2 = poly_2 - poly_1;
    delta_1 = (f_at_1 - f(poly_0)) / h_1;
    delta_2 = (f_at_2 - f_at_1) / h_2;
    d = (delta_2 - delta_1) / (h_1 + h_2);
    n += 1;
  }

  Err("Muller: maximum iterations exceeded".to_owned())
}
*/