拉格朗日插值法(c++)

已给sin0.32=0.314567sin0.34=0.333487sin0.36=0.352274,计算sin0.3367的值

#include <iostream>

#include<iomanip>

#include <cmath>

using namespace std;

int main()

{

      double numerator_cofficient;      //用来记录插值分子的乘积结果

      double denominator_coefficient;      //用来记录插值分母乘积的结果

      double input_x;      //需要输入的x的值

      double x[3]={0.32,0.34,0.36};      //已知x的值

      double y[3]={0.314567,0.333487,0.352274};      //已知y的值

      double result=0;      //用来记录插值结果

      

      cout<<"通过拟合得到的拉格朗日多项式为:"<<endl;

      for (int i=0;i<3;i++)

      {

            denominator_coefficient=1;

            cout<<y[i]<<"*";

            for (int j=0;j<3;j++)

            {

                  if (i==j)

                        continue;

                  cout<<"("<<"x-"<<x[j]<<")";

            }

            cout<<"/";

            for (int j=0;j<3;j++)

            {

                  if (i==j)

                        continue;

                  denominator_coefficient*=(x[i]-x[j]);

            }

            cout<<denominator_coefficient<<"*"<<"("<<"x-"<<x[i]<<")";

            if (i<3)

            {

                  cout<<"+";

            }

      }

      cout<<endl;

      

      cout<<"请输入需要插值的x:";

      cin>>input_x;

      for (int i=0;i<3;i++)

      {

            numerator_cofficient=1;

            denominator_coefficient=1;

            for (int j=0;j<3;j++)

            {

                  if (i==j)

                        continue;

                  numerator_cofficient*=(input_x-x[j]);

            }

            for (int j=0;j<3;j++)

            {

                  if (i==j)

                        continue;

                  denominator_coefficient*=(x[i]-x[j]);

            }

            result+=(y[i]*numerator_cofficient/denominator_coefficient);

      }

      cout<<"插值结果为:"<<setiosflags(ios::fixed)<<setprecision(10)<<result<<endl;

      cout<<"函数的真实值:"<<sin(0.3367)<<endl;

      cout<<"计算误差为:"<<100*(abs(result-sin(0.3367))/sin(0.3367))<<"%"<<endl;

      return 0;

}

posted @ 2015-11-27 23:53  硫酸亚铜  阅读(1790)  评论(0编辑  收藏  举报