#include<iostream>
using namespace std;
class Point{
public:
double x,y;
Point(double x, double y):x(x),y(y){}
};
class Lagrange{
public:
double getPrimaryFunctionValue(double x, int k);
double getValue(double x);
void setPoints(Point* ps, int n);
private:
Point* ps;
int n;
};
void Lagrange::setPoints(Point* ps, int n){
this->ps = ps;
this->n = n;
}
double Lagrange::getPrimaryFunctionValue(double x, int k){
double son = 1, mother = 1;
for(int i = 0; i < n; i++){
if(k != i){
son *= (x - ps[i].x);
mother *= (ps[k].x - ps[i].x);
}
}
return son/mother;
}
double Lagrange::getValue(double x){
double result = 0;
for(int i = 0; i < n; i++){
result += getPrimaryFunctionValue(x, i) * ps[i].y;
}
return result;
}
int main(){
Lagrange lg;
Point p[] = {Point(0.4,0.41075),Point(0.55,0.57815),Point(0.8,0.88811),Point(0.9,1.02652),Point(1,1.17520)};
lg.setPoints(p, 5);
cout<<lg.getValue(0.5)<<endl;
cout<<lg.getValue(0.7)<<endl;
cout<<lg.getValue(0.85)<<endl;
return 0;
}
【计算方法实验】实验5:拉格朗日插值
最新推荐文章于 2021-06-28 01:03:17 发布
本文介绍了一个使用C++实现的拉格朗日插值法程序,该程序定义了`Point`类来表示二维坐标点,并通过`Lagrange`类实现了拉格朗日插值法的基本功能。`Lagrange`类包括设置插值点、计算基函数值以及计算给定x值下的插值结果等方法。

726

被折叠的 条评论
为什么被折叠?



