拉格朗日插值程序实现

源之:

   http://www.programfan.com/blog/article.asp?id=15604

 

#include <iostream>
using namespace std;

void main()
{
 float **a,x,result;
 int n,i;
 float lglr(float **a,int n,float x);
 cout<<"输入点数:";
 cin>>n;
 a=new float *[n];
 for(i=0;i<n;i++)
  a[i]=new float[2];
 cout<<"输入各个点:"<<endl;
 for(i=0;i<n;i++)
  for(int j=0;j<2;j++)
   cin>>a[i][j];
 cout<<"输入自变量的值:";
 cin>>x;
 result=lglr(a,n,x);
 cout<<"运算结果是:"<<result<<endl;
}

float lglr(float **a,int n,float x)
{
 float result=0,xiang;
 for(int i=0;i<n;i++)
 {
  xiang=a[i][1];
  for(int j=0;j<n;j++)
   if(j!=i)
    xiang=xiang*(x-a[j][0])/(a[i][0]-a[j][0]);
  result=result+xiang;
 }
 return result;
}

 

后来我有改进了一下写法,毕竟二次指针不是那么直观,改动如下:

#include <iostream>
using namespace std;

typedef struct {
 float x;   // first
 float y;   // second
}Cord;

float lglr(Cord *a , int n , float x )
{
 float result = 0, xiang;
 for(int i=0;i<n;i++)
 {
  xiang = a[i].y;
  for(int j=0;j<n;j++)
   if(j!=i)
    xiang = xiang*(x-a[j].x)/(a[i].x-a[j].x);
  result = result + xiang;
 }
 return result;
}

void main()
{
 Cord *a ;
 float x,result;
 int n ,i;
 cout<<"please input the numbers of coords:";
 cin>>n;
 a = new Cord[n];
 cout<<"please input the coords:"<<endl;
 for(int i=0;i<n;i++)
 {
  cin>>a[i].x;
  cin>>a[i].y;
 }
 cout<<"please input the x"<<endl;
 cin>>x;
 result = lglr(a,n,x);
 cout<<"the result of the lglr:"<<result;
 delete[] a;
 while(1)
 {

 }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值