Debian Codegraph @

debian/rust-vendor/statrs/src/function/evaluate.rs

raw
1 //! Provides functions that don't have a numerical solution and must
2 //! be solved computationally (e.g. evaluation of a polynomial)
3
4 /// evaluates a polynomial at `z` where `coeff` are the coeffecients
5 /// to a polynomial of order `k` where `k` is the length of `coeff` and the
6 /// coeffecient
7 /// to the `k`th power is the `k`th element in coeff. E.g. [3,-1,2] equates to
8 /// `2z^2 - z + 3`
9 ///
10 /// # Remarks
11 ///
12 /// Returns 0 for a 0 length coefficient slice
13 pub fn polynomial(z: f64, coeff: &[f64]) -> f64 {
14 let n = coeff.len();
15 if n == 0 {
16 return 0.0;
17 }
18
19 let mut sum = *coeff.last().unwrap();
20 for c in coeff[0..n - 1].iter().rev() {
21 sum = *c + z * sum;
22 }
23 sum
24 }
25
26 #[rustfmt::skip]
27 #[cfg(test)]
28 mod tests {
29 use std::f64;
30
31 // these tests probably could be more robust
32 #[test]
33 fn test_polynomial() {
34 let empty: [f64; 0] = [];
35 assert_eq!(super::polynomial(2.0, &empty), 0.0);
36
37 let zero = [0.0];
38 assert_eq!(super::polynomial(2.0, &zero), 0.0);
39
40 let mut coeff = [1.0, 0.0, 5.0];
41 assert_eq!(super::polynomial(2.0, &coeff), 21.0);
42
43 coeff = [-5.0, -2.0, 3.0];
44 assert_eq!(super::polynomial(2.0, &coeff), 3.0);
45 assert_eq!(super::polynomial(-2.0, &coeff), 11.0);
46
47 let large_coeff = [-1.35e3, 2.5e2, 8.0, -4.0, 1e2, 3.0];
48 assert_eq!(super::polynomial(5.0, &large_coeff), 71475.0);
49 assert_eq!(super::polynomial(-5.0, &large_coeff), 51225.0);
50
51 coeff = [f64::INFINITY, -2.0, 3.0];
52 assert_eq!(super::polynomial(2.0, &coeff), f64::INFINITY);
53 assert_eq!(super::polynomial(-2.0, &coeff), f64::INFINITY);
54
55 coeff = [f64::NEG_INFINITY, -2.0, 3.0];
56 assert_eq!(super::polynomial(2.0, &coeff), f64::NEG_INFINITY);
57 assert_eq!(super::polynomial(-2.0, &coeff), f64::NEG_INFINITY);
58
59 coeff = [f64::NAN, -2.0, 3.0];
60 assert!(super::polynomial(2.0, &coeff).is_nan());
61 assert!(super::polynomial(-2.0, &coeff).is_nan());
62 }
63 }