legendre.cpp
来自「Legendre正交多项式拟合,可对任意曲线进行拟合」· C++ 代码 · 共 47 行
CPP
47 行
#include <assert.h>
#include <math.h>
#include <vector>
float Legendre(float x, int n)
{
assert(x >= -1 && x <= 1);
double ret;
if (n == 0)
ret = 1;
else
{
float ppre = 0, pre = 1;
for (int i = 1; i <= n; ++ i)
{
ret = ((2 * i - 1) * x * pre - (i - 1) * ppre) / i;
ppre = pre;
pre = ret;
}
}
// 下面是为了归一化起见,使Legendre(x, n) * Legendre(x, n) = 1
ret *= sqrt((2 * n + 1) / 2);
return ret;
}
std::vector<float> BestLegendre(float* x, float* y, int size, int n)
{
std::vector<float> alphaVec(n + 1);
float temp1 = (x[size - 1] - x[0]) / 2;
float temp2 = (x[size - 1] + x[0]) / 2;
float temp;
for (int i = 0; i <= n; ++ i)
{
for (int j = 0; j < size; ++ j)
{
temp = (x[j] - temp2) / temp1;
alphaVec[i] += Legendre(temp, i) * y[j];
}
alphaVec[i] /= size;
}
return alphaVec;
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?