Skip to content

Instantly share code, notes, and snippets.

@pr1ncess-emily
Last active November 12, 2022 00:25
Show Gist options
  • Save pr1ncess-emily/f0f55acc29897952a6143c2e1a5dda24 to your computer and use it in GitHub Desktop.
Save pr1ncess-emily/f0f55acc29897952a6143c2e1a5dda24 to your computer and use it in GitHub Desktop.
A small proof of concept for evaluating polynomial functions in Rust
struct Polynomial<'a> {
terms: &'a [PolynomialTerm],
}
impl<'a> Polynomial<'a> {
pub fn from_terms(terms: &'a [PolynomialTerm]) -> Self {
Self { terms }
}
pub fn eval_with_value(&self, value: f64) -> f64 {
self.terms
.iter()
.map(|term| match term {
PolynomialTerm::Variable(t) => t.eval_with_value(value),
PolynomialTerm::Constant(c) => *c,
})
.sum()
}
}
enum PolynomialTerm {
Variable(VariableTerm),
Constant(f64),
}
struct VariableTerm {
coeffecient: f64,
exponent: i32,
}
impl VariableTerm {
pub fn declare(coeffecient: f64, exponent: i32) -> Self {
Self {
coeffecient,
exponent,
}
}
pub fn eval_with_value(&self, value: f64) -> f64 {
self.coeffecient * (value.powi(self.exponent))
}
}
macro_rules! term {
// like -3.1 * x * 3
($coefficient:literal*x^$exponent:literal) => {{
PolynomialTerm::Variable(VariableTerm::declare($coefficient as f64, $exponent as i32))
}};
// like 4.21 * x
($coefficient:literal*x) => {{
PolynomialTerm::Variable(VariableTerm::declare($coefficient as f64, 1i32))
}};
// like 5
($constant:literal) => {{
PolynomialTerm::Constant($constant as f64)
}};
}
fn main() {
// f(x) = 3x^2 - 5x + 1
// f(6) = 79
let terms: [PolynomialTerm; 3] = [term!(3 * x ^ 2), term!(-5 * x), term!(1.0)];
let poly = Polynomial::from_terms(&terms);
assert_eq!(79.0, poly.eval_with_value(6.0));
}
@pr1ncess-emily
Copy link
Author

Now with improved syntax!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment