polynomial_roots/linear/
mod.rs

1/// Returns a vector with the real roots of the polynomial
2/// obtained with the linear formula.
3/// x = -b / a
4/// The roots are in increasing order.
5pub fn get_roots(
6  polynomial: &crate::polynomials::Polynomial,
7  has_zero: bool,
8) -> Vec<f32> {
9  if let (Some(a), Some(b)) =
10    (polynomial.last(), polynomial.first())
11  {
12    let root = -b / a;
13
14    if has_zero {
15      // Ensure the roots are ordered.
16      if root > 0.0 {
17        vec![0.0, root]
18      } else {
19        vec![root, 0.0]
20      }
21    } else {
22      vec![root]
23    }
24  } else {
25    vec![]
26  }
27}
28
29#[cfg(test)]
30mod tests {
31  #[test]
32  fn polynomial_with_one_root() {
33    let polynomial = crate::polynomials::Polynomial::new(
34      std::collections::LinkedList::from([1.0, 2.0]),
35    );
36    assert_eq!(
37      crate::linear::get_roots(&polynomial, false),
38      vec![-0.5],
39    );
40  }
41
42  #[test]
43  fn polynomial_with_two_roots() {
44    let polynomial = crate::polynomials::Polynomial::new(
45      std::collections::LinkedList::from([-2.0, 1.0]),
46    );
47    assert_eq!(
48      crate::linear::get_roots(&polynomial, true),
49      vec![0.0, 2.0],
50    );
51  }
52}