拉格朗日函数c++
#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;
}
附件列表
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。