C語言 習題1-1-a 請用Lanrange內差法寫出下列諸點的方程式
x f(x)
============
0.0 0.00
1.0 -3.00
2.0 0.00
34.0 15.00
============
並計算 P[0.5 , 1.5 .2.5 ,3.5] 之值並與 f(x)=x^3 -4 x 的誤差
程式
/* ex1-4.c: Lagrange Interpolation Algorithm
* Read in data file of ex1-4.dat which has n point values
* and the value of interpolating point xa. Based on Lagrange
* Interpolation algorithm to compute p(xa) and output its value.
* (x[i],f[i]):given points and n+1 are number of points
* Ln,k(x)=l=summation of (x-x[i])/(x[k]-x[i]).
* p(x)=ff=L(x)*f(x[k])
*/
#include <stdio.h>
//#include <conio.h>
//#include <math.h>
int main()
{
double x[30],f[30],l,ff,xa[30],xb;
int i,k,n ,n1 ,j ;
scanf("n=%d n1=%d",&n,&n1);
getch();
for(k=0;k<=n;k++)
{
scanf("%lf %lf",&x[k],&f[k]);
getch();
}
for(k=0;k<=n1;k++)
{
scanf("%lf",&xa[k]);
getch();
//printf("The value of p(%.4lf)\n",xa[k]);
}
for (j=0;j<=n1;j++)
{
xb=xa[j];
//printf("The value of p(%.4lf)\n",xb);
ff=0.0;
for(k=0;k<=n;k++)
{
l=1.0;
for(i=0;i<=n;i++)
{
if(i !=k)
{
l=l*(xb-x[i])/(x[k]-x[i]);
getch();
}
}
ff=ff+l*f[k];
}
printf("The value of p(%.4lf)=%.4lf\n",xb,ff);
printf("The value of f(%.4lf)=%.4lf\n",xb,(xb*xb*xb-4*xb));
printf("The value of | p(%.4lf)-f(%.4lf)|=%.6lf\n",xb,xb, ((xb*xb*xb-4*xb)-ff) );
}
return 0;
}
輸入資料
n=3 n1=3
0.0 0.0
1.0 -3.0
2.0 0.0
3.0 15.0
0.5
1.5
2.5
3.5
輸出畫面
The value of p(0.5000)=-1.8750
The value of f(0.5000)=-1.8750
The value of | p(0.5000)-f(0.5000)|=0.000000
The value of p(1.5000)=-2.6250
The value of f(1.5000)=-2.6250
The value of | p(1.5000)-f(1.5000)|=0.000000
The value of p(2.5000)=5.6250
The value of f(2.5000)=5.6250
The value of | p(2.5000)-f(2.5000)|=0.000000
The value of p(3.5000)=28.8750
The value of f(3.5000)=28.8750
The value of | p(3.5000)-f(3.5000)|=0.000000
沒有留言:
張貼留言