【发布时间】:2020-06-09 07:23:30
【问题描述】:
我需要在多个点上评估某个程度 (p(x) = 4x^3 + 2*x^2 -2*x + 5 时,x = 0, x= 2 结果应该是:[5, 41]。
找不到与 Matlab 的 Polyval 等效的函数。
结果的准确性对我来说并不重要(可以四舍五入为整数),但计算时间是。
我的直截了当的解决方案:
#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;
}
}
不确定在性能方面是否有更好的方法。
【问题讨论】:
-
你可以放弃
std::pow作为初学者,并在你去的时候积累x的力量。请参阅下一条注释了解此方法的名称: -
除非您的应用程序的运行时间上限为微秒级,否则我认为优化简单的 for 循环不会对您的代码产生任何影响。 “过早的优化是万恶之源”
-
从0度开始,积累价值的力量。根本不需要使用
std::pow()。
标签: c++ matlab polynomials polynomial-math