C++实训--拉氏插值
2019-04-29 本文已影响8人
简言之_
image.png
方法一:
//根据所给数据点个数,自动选择拉氏多项式的次数并进行插值
#include <iostream>
using namespace std;
//预先定义插值节点的个数为1000个,根据控制台输入的个数num从而确定插值节点的个数
const int N = 1000;
//arrX[N],arrY[N]分别存放的是插值节点(Xi,Yi)中的Xi,Yi,参数n为插值节点的个数,而参数x为待求解的插值节点的X值
//函数返回值为求解出来的插值节点X对应的Y值
//注意整个过程涉及的变量,除了循环变量为int外,其他均为double
double Lagrange(double arrX[], double arrY[], int n, double x)
{
double yResult = 0.0;
//LValue[N]存放的是每次求解的插值基函数的通项
double LValue[N];
//循环变量i,j
int i, j;
//插值基函数中的上下累乘temp1,temp2
double temp1, temp2;
for (i = 0; i < n; i++)
{
temp1 = 1.0;
temp2 = 1.0;
for (j = 0; j < n; j++)
{
if (j == i)
{
continue;
}
temp1 *= (x - arrX[j]);
temp2 *= (arrX[i] - arrX[j]);
}
LValue[i] = temp1 / temp2;
}
for (int k = 0; k < n; k++)
{
yResult += arrY[k] * LValue[k];
}
return yResult;
}
int main()
{
double arrX[N], arrY[N];
int num;
cout << "输入插值节点的个数(小于" << N << "个): ";
cin >> num;
cout << "\n--接下来输入这些插值节点(先输入X 再输入对应的Y)--\n";
for (int i = 0; i < num; i++)
{
cout << "第" << i + 1 << "个节点的X值: ";
cin >> arrX[i];
cout << "第" << i + 1 << "个节点的Y值: ";
cin >> arrY[i];
}
double X = 0;
while (X != -1)
{
cout << "\n--请输入待求解的插值节点的X值--\n";
cin >> X;
if (X == -1) {
cout << "结束\n";
return 0;
}
double Res = Lagrange(arrX, arrY, num, X);
cout << "\n--插值结果为: " << Res << endl;
}
return 0;
}
方法二:
#include<iostream>
using namespace std;
struct point
{
double x;
double y;
};
double f(double x)
{
return x*x*x-x*x+2*x-6;
}
double initps(point *p,int size)
{
for (int i = 0; i < size; ++i)
{
p[i].x=0.2*i;
p[i].y=f(p[i].x);
}
}
double lglr(double x,point *p,int n)
{
double s=0;
for (int i = 0; i <= n; ++i)
{
double f=1;
for (int j = 0; j <= n; ++j)
if(i!=j)
{f*=(x-p[j].x)/(p[i].x-p[j].x);}
s+=p[i].y*f;
}
return s;
}
int main ()
{
point ps[10];
initps(ps,10);
cout<<f(0.5)<<" "<<lglr(0.5,ps,9)<<endl;
return 0;
}