#[allow(rustdoc::broken_intra_doc_links)]
pub struct Polynomial<T> {
pub coef: Vec<T>,
pub order: usize,
}
impl<T: num::Float> Polynomial<T> {
pub fn new(coef: Vec<T>) -> Self {
let order = coef.len() - 1;
Polynomial { coef, order }
}
pub fn eval(&self, x: T) -> T {
let last_idx = self.order;
let mut res = self.coef[last_idx];
for i in (1..=last_idx).rev() {
res = self.coef[i - 1] + x * res
}
res
}
pub fn eval_derivs(&self, x: T, n: usize) -> Vec<T> {
let mut res: Vec<T> = vec![T::zero(); n];
let lenres = res.len();
let lenpoly = self.coef.len(); let last_idx = self.order;
let nmax = lenpoly.min(lenres) - 1;
for d in res.iter_mut().take(nmax + 1) {
*d = self.coef[last_idx]
}
for i in 0..last_idx {
let k = last_idx - i;
res[0] = x * res[0] + self.coef[k - 1];
let jmax = if nmax < k { nmax } else { k - 1 };
for j in 1..=jmax {
res[j] = x * res[j] + res[j - 1];
}
}
let mut f = T::one();
for (i, d) in res.iter_mut().enumerate().take(nmax + 1).skip(2) {
f = f * T::from(i).unwrap();
*d = *d * f;
}
res
}
}