scicpp::polynomial::Polynomial

Defined in header <scicpp/polynomials.hpp>


template<typename T>
class Polynomial

The Polynomial class provides operators for:

arithmetic:+, -, *, +=, -=, *=
comparison:== (exact equality, see also is_approx), !=
evaluation:().

Constructors


Polynomial(std::size_t deg)

Initialize a Polynomial of a degree deg with zero coefficients.


Polynomial(const std::vector<T> &coef)
Polynomial(std::vector<T> &&coef)

Initialize a Polynomial from a std::vector of coefficients.

parameter coef:Polynomial coefficients in order of increasing degree, i.e., {1., 2., 3.} is \(1 + 2 X + 3 X^{2}\).

template<std::size_t N>
Polynomial(const std::array<T, N> &coef)

Initialize a Polynomial from a std::array of coefficients.


template<class Iterator>
Polynomial(Iterator first, Iterator last)

Initialize a Polynomial from an iterator.


Polynomial(std::initializer_list<T> l)

Initialize a Polynomial from an initializer list.

Methods


std::size_t degree() const

Return the polynomial degree.


const std::vector<T> &data() const

Return the polynomial coefficients in a std::vector of size degree + 1.


void mulx()

Multiply the polynomial by \(X\).


void trim(T tol = 0)

Remove trailing coefficients smaller than tol from the polynomial.


void reserve(std::size_t n_coefs)

Reserve the memory to store a number n_coefs of coefficients.


template<int rel_tol = 16>
bool is_approx(const Polynomial &rhs) const

Check whether two polynomials are approximately equal. That is whether they have the same degree and if the relative distance between each corresponding coefficient in units of epsillon is smaller than rel_tol.

Example

#include <cstdio>
#include <scicpp/polynomials.hpp>

int main()
{
    scicpp::polynomials::Polynomial P1{1., 2., 3.};
    scicpp::polynomials::Polynomial P2{9., 5., 1.};
    auto P = 2. * P1 * P2;

    // Print the resulting polynomial degree
    printf("deg(P) = %lu\n", P.degree());

    // Evaluate the polynomial for x = 3.14
    printf("P(3.14) = %f\n", P(3.14));
}