libcruft-util/cruft/util/polynomial.hpp

40 lines
945 B
C++
Raw Permalink Normal View History

2015-01-21 23:40:45 +11:00
/*
2018-08-04 15:14:06 +10:00
* 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/.
2015-01-21 23:40:45 +11:00
*
* Copyright 2015 Danny Robson <danny@nerdcruft.net>
*/
#ifndef CRUFT_UTIL_POLYNOMIAL_HPP
#define CRUFT_UTIL_POLYNOMIAL_HPP
2015-01-21 23:40:45 +11:00
#include <array>
#include <cstdlib>
namespace cruft::polynomial {
2016-12-21 20:21:28 +11:00
// 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>);
2015-01-21 23:40:45 +11:00
2016-12-21 20:21:28 +11:00
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;
}
2015-01-21 23:40:45 +11:00
return sum;
}
}
2015-01-21 23:40:45 +11:00
#endif