libcruft-util/polynomial.hpp

40 lines
945 B
C++

/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright 2015 Danny Robson <danny@nerdcruft.net>
*/
#ifndef CRUFT_UTIL_POLYNOMIAL_HPP
#define CRUFT_UTIL_POLYNOMIAL_HPP
#include <array>
#include <cstdlib>
namespace cruft::polynomial {
// Invalid solutions are represented by NaN. They are guaranteed to
// be at the end of the solution list, so they are safe to skip on the
// first instance.
template <size_t S>
std::array<float,S>
roots (std::array<float,S+1>);
template <size_t S, typename T, typename U>
T
eval (std::array<T,S> coeffs, U x)
{
U x_ = 1.f;
T sum {0.f};
for (size_t i = 0; i < S; ++i) {
sum += coeffs[S-i-1] * x_;
x_ *= x;
}
return sum;
}
}
#endif