拉格朗日插值多項式
插值的定義:
- 線性插值
插值基函數
-
二次插值
-
n次拉格朗日插值多項式
可以由線性插值和二次插值的規律可循:
其中: 省略第k項
上機操作代碼:
//驗證拉格朗日插值法求近似值
#include<iostream>
using namespace std;
//已知點座標
struct Point
{
double x, y;
};
double LagrangeInsert(double x,Point* point, int n)
{
double temp1 = 1, temp2 = 1,result = 0;
for(int m=0;m<n;m++)
{
for (int i = 0; i < n; i++)
{
if (i != m)
{ //求分子
temp1 *= (x - point[i].x);
//求分母
temp2 *= (point[i].x - point[m].x);
}
}
//得出Lm(x)的結果
result += ((temp1 / temp2)*point[m].y);
temp1 = 1;
temp2 = 1;
}
return result;
}
//測試函數
int main()
{
Point point[100];
int n;
cout << "Please input the number of points\n";
cin >> n;
for (int i = 0; i < n; i++)
{
cout << "No" << i+1 <<":"<< "x" << endl;
cin >> point[i].x;
cout << "No" << i+1 <<":"<< "y" << endl;
cin >> point[i].y;
}
cout << "Please input a value to verify the result\n";
double x;
cin >> x;
cout<<"Ruslt:"<<LagrangeInsert(x, point, n)<<endl;
}
實驗結果
例:
已知四個點(-2.00,17.00),(0.00,1.00),(1.00,2.00),(2.00,17.00)來計算 f(0.6)