实验内容
1、通过全区间上拉格朗日插值计算f(0.15),f(0.31),f(0.47)的近似值。
x 0.0 0.1 0.195 0.3 0.401 0.5
f(x) 0.39894 0.39695 0.39142 0.38138 0.36812 0.35206
2、给定函数f(x)=√x,已知:
f(2.0)=1.414214, f(2.1)=1.449138, f(2.2)=1.48320, f(2.3)=1.516575, f(2.4)=1.549193
用牛顿插值法求4次Newton插值多项式在2.15处的值,以此作为函数的近似值√2.15≈N(2.15).
#include<iostream>
#include<iomanip>
using namespace std;
double Lagrange(double* x, double* y, int n, double t){
if (n < 0) {
throw("can't use this way,not enough data point!!");
return 0;
}
if (n == 1) return y[0];
if (n == 2) return ((y[0] * (t - x[1]) - y[1] * (t - x[0])) / (x[1] - x[0]));
int i = 0;
while ((t > x[i]) &&(t < n))
i++;
int k = i - 4;
if (k < 0) k = 0;
int m = i + 3;
if (m > n - 1) m = n - 1;
double result=0.0;
for (int j = k; j <= m; j++) {
double s = 1;
for (int l = k; l < m; l++)
if (j != l)
s *= (t - x[l]) / (x[j] - x[l]);
result += y[j] * s;
}
return result;
}
int main(){
double aa = 0.15;
double bb = 0.31;
double cc = 0.47;
double c;
double a[6] = { 0.0,0.1,0.195,0.3,0.401,0.5 };
double b[6] = { 0.39894,0.39695,0.39142,0.38138,0.36812,0.35206 };
c = Lagrange(a, b, 6, aa);
cout << setprecision(8) <<"f(0.15) = " << c << endl;
c = Lagrange(a, b, 6, bb);
cout <<"f(0.31) = " << c << endl;
c = Lagrange(a, b, 6, cc);
cout << "f(0.47) = " <<c << endl;
return 0;
}
#include<iostream>
#include<string>
#include<vector>
using namespace std;
double DifferenceQuotient(int n,vector<double>&X,vector<double>&Y);
double NewtonInterpolationMethod(double x,vector<double>&X,vector<double>&Y);
int main(){
int n;
cin>>n;
vector<double>X(n,0);
vector<double>Y(n,0);
for(int i=0;i<n;i++){
cin>>X[i]>>Y[i];
}
double x;
cin>>x;
cout<<NewtonInterpolationMethod(x,X,Y);
}
double DifferenceQuotient(int n,vector<double>&X,vector<double>&Y){
double f=0;
double temp=0;
for(int i=0;i<n+1;i++){
temp=Y[i];
for(int j=0;j<n+1;j++)
if(i!=j) temp /= (X[i]-X[j]);
f += temp;
}
return f;
}
double NewtonInterpolationMethod(double x,vector<double>&X,vector<double> &Y){
double result=0;
for(int i=0;i<X.size();i++){
double temp=1;
double f=DifferenceQuotient(i,X,Y);
for(int j=0;j<i;j++){
temp = temp*(x-X[j]);
}
result += f*temp;
}
return result;
}