I need to evaluate a polynomial (1 dimension) of some degree (<10) in multiple points.
For instance, when calculating for polynomial p(x) = 4x^3 + 2*x^2 -2*x + 5
, at x = 0, x= 2
result should be : [5, 41]
.
Couldn't find an equivalent function to Matlab's Polyval.
The result accuracy is not critical for me (can be rounded to integer) but the calculation time is.
My straight-forward solution:
#include<iostream>
#include<vector>
#include<math.h>
std::vector<double> Polyval(std::vector<double> coeffs, std::vector<double> values)
{
std::vector<double> results;
for (auto const &val:values)
{
double result = 0;
for (int i = 0, deg = coeffs.size() - 1; deg >= 0; deg--, i++)
{
result += coeffs[i] * std::pow(val, deg);
}
results.push_back (result);
}
return results;
}
int main()
{
std::vector<double> coeffs = { 4, 2, -2, 5};
std::vector<double> valuesToEvaluate = { 0, 2 , -4};
std::vector<double> results = Polyval (coeffs, valuesToEvaluate);
for (auto const &res:results)
{
std::cout << res << std::endl;
}
}
Not sure if there is a better way in terms of performance.