本程序对cosx函数进行插值,取步长为0.1,因此x的值为0.00,0.10,0.20,0.30,对应的y值为cos(0.00),cos(0.10),cos(0.20),cos(0.30),其实本程序Horner方法(又称秦九韶算法)效率更高,计算更加准确
#include <iostream>
#include <cmath>
using namespace std;
int factorial(int n); //声明阶乘函数
double average_deviation(double* function_value,double& h,int end); //声明均差函数
int main()
{
double h=0.10; //计算的步长
double x[4]={0.00,0.10,0.20,0.30}; //用来存储已知x的值
double y[4]={cos(0.00),cos(0.10),cos(0.20),cos(0.30)}; //用来存储已知y的值
double result=0; //用来保存最后的插值结果
double input_x; //插值的x值
double polynomial; //保存多项式的值
cout<<"通过插值得到的函数为:"<<endl;
for (int i=0;i<4;i++)
{
cout<<average_deviation(y,h,i)/(factorial(i))/pow(h,i);
for (int j=0;j<i;j++)
cout<<"*"<<"("<<"x-"<<x[j]<<")";
if (i<3&&((average_deviation(y,h,i+1)/(factorial(i+1))/pow(h,i+1))>0))
cout<<"+";
}
cout<<endl;
cout<<"请输入插值的x值:";
cin>>input_x;
for (int i=0;i<4;i++)
{
polynomial=1;
for (int j=0;j<i;j++)
{
polynomial*=(input_x-x[j]);
}
result+=(average_deviation(y,h,i)/(factorial(i))/pow(h,i)*polynomial);
}
cout<<"插值得到的函数值为:"<<result<<endl;
cout<<"函数的真实值为:"<<cos(input_x)<<endl;
cout<<"误差为:"<<100*((result-cos(input_x))/cos(input_x))<<"%"<<endl;
return 0;
}
int factorial(int n)
{
if (n<0)
{
cout<<"请输入正整数值"<<endl;
exit(0);
}
else if (n==0)
return 1;
else
return n*factorial(n-1);
}
double average_deviation(double* function_value,double& h,int end)
{
double* function_value_f; //function_value_f用来保存0到k-1的k阶差分
double* function_value_b; //function_value_f用来保存1到k的k阶差分
double value_f;
double value_b;
if (0==end)
{
return function_value[end];
}
else
{
function_value_f=new double[end];
function_value_b=new double[end];
for (int i=1;i<=end;i++)
function_value_f[i-1]=function_value[i];
for (int i=0;i<=end-1;i++)
function_value_b[i]=function_value[i];
value_f = average_deviation(function_value_f,h,end - 1);
value_b = average_deviation(function_value_b,h, end - 1);
delete[] function_value_f;
delete[] function_value_b;
return value_f-value_b;
}
}