polynomial_tools/
linear.rs

1use std::{fmt, ops};
2use super::{s_val_last, display_header};
3use super::{Quadratic, Polynomial};
4/// A struct that contains the constants of an equation
5/// in the form ax + b.
6/// Some useful functions are also implemented.
7#[derive(Debug, Clone, Copy, PartialEq)]
8pub struct Linear {
9  pub a: f64,
10  pub b: f64
11}
12
13impl fmt::Display for Linear {
14  /// Displays the Linear.
15  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
16    let part1 = display_header(self.a, String::from("x"));
17    let part2 = s_val_last(self.b);
18    write!(f, "{part1}{part2}")
19  }
20}
21
22impl ops::Add<Linear> for Linear {
23  type Output = Self;
24  fn add(self, other: Self) -> Self::Output {
25    Self::new(
26      self.a + other.a, 
27      self.b + other.b
28    )
29  }
30}
31
32impl ops::Add<f64> for Linear {
33  type Output = Self;
34  fn add(self, other: f64) -> Self::Output {
35    Self::new(self.a, self.b + other)
36  }
37}
38
39impl ops::Sub<Linear> for Linear {
40  type Output = Self;
41  fn sub(self, other: Self) -> Self::Output {
42    Self::new(
43      self.a - other.a, 
44      self.b - other.b
45    )
46  }
47}
48
49impl ops::Sub<f64> for Linear {
50  type Output = Self;
51  fn sub(self, other: f64) -> Self::Output {
52    Self::new(self.a, self.b - other)
53  }
54}
55
56impl ops::Mul<Linear> for Linear {
57  type Output = Quadratic;
58  fn mul(self, other: Linear) -> Self::Output {
59    Self::Output::new(
60      self.a * other.a,
61      self.a * other.b + self.b * other.a,
62      self.b * other.b
63    )
64  }
65}
66  
67impl ops::Mul<f64> for Linear {
68  type Output = Self;
69  fn mul(self, other: f64) -> Self::Output {
70    Self::new(self.a * other, self.b * other)
71  }
72}
73
74impl Polynomial for Linear {
75  /// Evaluates the Linear at the given x.
76  fn evaluate(&self, x: f64) -> f64 {
77    (self.a * x) +
78    self.b
79  }
80  fn is_zero(&self) -> bool {
81    self.a == 0.0 &&
82    self.b == 0.0
83  }
84  fn degree(&self) -> u8 { 1 }
85
86  type Derivative = f64;
87  fn derivative(&self) -> Self::Derivative {
88    self.a
89  }
90}
91
92impl Linear {
93  /// Creates a new Linear from the values given.
94  pub fn new(a: f64, b: f64) -> Self {
95    Self { a, b }
96  }
97
98  /// Creates a new Linear from the values given.
99  pub fn new_i(a: i32, b: i32) -> Self {
100    Self {
101      a: a.into(),
102      b: b.into()
103    }
104  }
105
106  /// Finds the root of the Linear
107  /// 
108  /// # Errors:
109  /// If no (or infinitely many) roots exist, an Err is returned.
110  pub fn root(&self) -> Result<f64, &str> {
111    if self.a == 0.0 {
112      return Err("a must be non-zero");
113    }
114    Ok(-(self.b / self.a))
115  }
116}