const_poly/
polynomial.rs

1use crate::term::Term;
2
3/// Represents a polynomial with a fixed number of variables and terms.
4///
5/// The polynomial is defined as a sum of `NUM_TERMS` terms, where each term
6/// operates on `NUM_VARIABLES` variables. Each term is an instance of `Term<N>`,
7/// encapsulating a coefficient and a set of variable functions.
8///
9/// # Type Parameters
10///
11/// - `NUM_VARIABLES`: Number of variables in the polynomial.
12/// - `NUM_TERMS`: Number of terms in the polynomial.
13///
14/// # Example
15///
16/// ```
17/// use const_poly::VarFunction::*;
18/// use const_poly::{const_poly, Polynomial};
19///
20/// // Create a polynomial, f(x,y) = 3 * sin(x) * cos(y)
21/// const POLY: Polynomial<2, 1> = const_poly!({[3.0, Sin, Cos]});
22///
23/// // Evaluate at x = π/2, y = 0 => 3 * sin(π/2) * cos(0) = 3 * 1 * 1 = 3
24/// let result = POLY.evaluate([1.57079632679, 0.0]);
25/// assert!((result - 3.0).abs() < 1e-6);
26/// ```
27pub struct Polynomial<const NUM_VARIABLES: usize, const NUM_TERMS: usize> {
28    terms: [Term<NUM_VARIABLES>; NUM_TERMS],
29}
30
31impl<const NUM_VARIABLES: usize, const NUM_TERMS: usize> Polynomial<NUM_VARIABLES, NUM_TERMS> {
32    /// Creates a new `Polynomial` from an array of terms.
33    ///
34    /// # Parameters
35    ///
36    /// - `terms`: An array containing `NUM_TERMS` terms, each of which operates on `NUM_VARIABLES` variables.
37    ///
38    /// # Returns
39    ///
40    /// A new `Polynomial` instance encapsulating the given terms.
41    ///
42    /// # Example
43    ///
44    /// ```
45    /// use const_poly::VarFunction::*;
46    /// use const_poly::{const_poly, Polynomial};
47    ///
48    /// //define polynomial f(x,y) = x*y + 2*Sin(x)*Sin(y)
49    /// const POLY: Polynomial<2, 2> = const_poly!({[1.0, Identity, Identity],
50    ///                                             [2.0, Sin,      Cos]});
51    /// ```
52    pub const fn new(terms: [Term<NUM_VARIABLES>; NUM_TERMS]) -> Self {
53        Self { terms }
54    }
55
56    /// Evaluates the polynomial at the given variable values.
57    ///
58    /// This computes the sum of the evaluations of all constituent terms.
59    ///
60    /// # Parameters
61    ///
62    /// - `vars`: An array of `NUM_VARIABLES` floating-point values representing the variables.
63    ///
64    /// # Returns
65    ///
66    /// The floating-point result of evaluating the polynomial.
67    pub const fn evaluate(&self, vars: [f64; NUM_VARIABLES]) -> f64 {
68        let mut sum = 0.0;
69        let mut i = 0;
70
71        while i < NUM_TERMS {
72            sum += self.terms[i].evaluate(vars);
73            i += 1;
74        }
75
76        sum
77    }
78}