用C#实现的等距Lagrange插值代码

来源:互联网 发布:php发送post get请求 编辑:程序博客网 时间:2024/05/16 11:04
 

class Program
    {
        //private double[] f = {1.1052,1.2214,1.3499,1.4918,1.6487};//实验数据一
        private double[] f = { -0.693147, -0.510826, -0.356675 };//实验数据二
        static void Main(string[] args)
        {
            double result;
            Program s=new Program();
           // result = s.GetValueLagrange(0.285,0.1,5,0.1);
            result = s.GetValueLagrange(0.54,0.1,3,0.5);
            Console.WriteLine("求e^0.285插值结果是: "+result);
            Console.ReadLine();
        }
      ///一元全区间等距插值

    ///@param n -- 节点个数

   ///@param  x -- 待求点的函数值

   ///@param h -- 节点搜索步长

   ///@param  y[i]  -- 一维数组,存放插值节点的值

  ///@param x0 -- 为插值初节点

   ///@param retturn double  ,还回所求函数的近似值 

      public double GetValueLagrange(double x, double h,int n,double x0)
        {
            double p=0.0;
            double[] y=new double[n];

            for(int i=0;i<n;i++)
            { 
                y[i]=x0+i*h;
            }
            for (int i = 0; i <n; i++)
            {
                double m=1.0;
                for(int j=0;j<n;j++)
                {
                    if (i == j && i < n - 1)
                    {
                        j++;
                        m = m * ((x - y[j]) / (y[i] - y[j]));
                    }
                    else
                        if (i == j && i == n - 1)
                               { continue; }
                    else
                    {
                        m = m * ((x - y[j]) / (y[i] - y[j]));
                    }
                }
                p += f[i] * m;
            }
            return p;
        }
    }

原创粉丝点击