polyfit_rs/
lib.rs

1extern crate nalgebra as na;
2
3pub mod polyfit_rs {
4
5    /// @param x_values The x-values
6    /// @param y_values The y-values
7    /// @param polynomial_degree The degree of the polynomial. I. e. 2 for a parabola.
8    /// @return Degree of monomials increases with the vector index
9    pub fn polyfit<T: na::RealField + Copy>(
10        x_values: &[T],
11        y_values: &[T],
12        polynomial_degree: usize,
13    ) -> Result<Vec<T>, &'static str> {
14        let number_of_columns = polynomial_degree + 1;
15        let number_of_rows = x_values.len();
16        let mut a = na::DMatrix::zeros(number_of_rows, number_of_columns);
17
18        for (row, &x) in x_values.iter().enumerate() {
19            // First column is always 1
20            a[(row, 0)] = T::one();
21
22            for col in 1..number_of_columns {
23                a[(row, col)] = x.powf(na::convert(col as f64));
24            }
25        }
26
27        let b = na::DVector::from_row_slice(y_values);
28
29        let decomp = na::SVD::new(a, true, true);
30
31        match decomp.solve(&b, na::convert(1e-18f64)) {
32            Ok(mat) => Ok(mat.data.into()),
33            Err(error) => Err(error),
34        }
35    }
36}