标签:
#include <iostream>
using namespace std;
//拉格朗日插值求解方程
double * xs; //all input x
double * ys; //all input y
int n; //size
//1.1275 1.1503 1.1735 1.1972
//0.1191 0.13954 0.15932 0.17903
//1.130
void init()
{
cout << "please input n " << endl;
cin >> n;
xs = new double[n];
ys = new double[n];
//input x
cout << "please input the x‘s value !" << endl;
for(int i=0; i<n; i++)
{
cin >> xs[i];
}
//input y
cout << "please input the y‘s value !" << endl;
for(int i=0; i<n; i++)
{
cin >> ys[i];
}
}
double everyItem(int num, double x)
{
double y = ys[num];
double up = 1;
double down = 1;
for(int i=0; i<n; i++)
{
if(i != num)
{
up *= (x - xs[i]);
down *= (xs[num] - xs[i]);
}
}
return y*up/down;
}
double lagrange(double x)
{
double total = 0;
for(int i=0; i<n; i++)
{
total = total + everyItem(i , x);
}
return total;
}
int main()
{
init();
double input;
cout << "please input you x !" <<endl;
cin >> input;
double result = lagrange(input);
cout << "the result is " << result << endl;
return 0;
}
标签:
原文地址:http://www.cnblogs.com/sober-reflection/p/28809f97512c2fa41aab75d0cb6866e6.html