求x=1.5 , 2,5 的值P(1.5)=? P(2.5)=?
並且與 f(x)=x^3 - 4x 做比較
n=5
x f(x)
=============
0.0 0.0
1.1 -3.0
2.0 0.0
3.0 15.0
4.0 48.0
=============
程式
/***************** Newtons interpolation **************/
#include <stdio.h>
int main()
{
int n,i,j,k,n1;
double x[20],f[20],a,sum=0.0,mult,xa[20];
scanf("n=%d a=%lf",&n,&a);
for(i=0;i<n;i++)
{
scanf("%lf %lf ",&x[i],&f[i]);
}
for(i=0;i<n1;i++)
{
scanf("%lf",&xa[i]);
}
for(i=0;i<n;i++)
{
printf("\ni=%2d x[i]=%0.2lf f[i]=%0.2lf" ,i,x[i],f[i]);
}
for(j=0;j<n-1;j++)
{
for(i=n-1;i>j;i--)
{
f[i]=(f[i]-f[i-1])/(x[i]-x[i-j-1]);
}
}
for(i=n-1;i>=0;i--)
{
mult=1;
for(j=0;j<i;j++)
mult*=(a-x[j]);
mult*=f[j];
sum+=mult;
}
printf("\nP(%0.2lf) ,The result is: %0.5lf",a,sum);
printf("\nf(%0.2lf) ,The result is: %0.5lf",a,(a*a*a-4*a));
printf("\nf(x)-P(x)=e(x)=%0.5lf",((a*a*a-4*a)-sum));
getch();
return 0;
}
輸入資料
n=5 a=1.5
0.0 0.0
1.0 -3.0
2.0 0.0
3.0 15.0
4.0 48.0
輸出畫面
i= 0 x[i]=0.00 f[i]=0.00
i= 1 x[i]=1.00 f[i]=-3.00
i= 2 x[i]=2.00 f[i]=0.00
i= 3 x[i]=3.00 f[i]=15.00
i= 4 x[i]=4.00 f[i]=48.00
P(1.50) ,The result is: -2.62500
f(1.50) ,The result is: -2.62500
f(x)-P(x)=e(x)=0.00000
輸入資料
n=5 a=2.5
0.0 0.0
1.0 -3.0
2.0 0.0
3.0 15.0
4.0 48.0
輸出畫面
i= 0 x[i]=0.00 f[i]=0.00
i= 1 x[i]=1.00 f[i]=-3.00
i= 2 x[i]=2.00 f[i]=0.00
i= 3 x[i]=3.00 f[i]=15.00
i= 4 x[i]=4.00 f[i]=48.00
P(2.50) ,The result is: 5.62500
f(2.50) ,The result is: 5.62500
f(x)-P(x)=e(x)=0.00000
輸入資料
n=5 a=2.5
0.0 0.0
1.0 -3.0
2.0 0.0
3.0 15.0
4.0 48.0
輸出畫面
i= 0 x[i]=0.00 f[i]=0.00
i= 1 x[i]=1.00 f[i]=-3.00
i= 2 x[i]=2.00 f[i]=0.00
i= 3 x[i]=3.00 f[i]=15.00
i= 4 x[i]=4.00 f[i]=48.00
P(2.50) ,The result is: 5.62500
f(2.50) ,The result is: 5.62500
f(x)-P(x)=e(x)=0.00000
沒有留言:
張貼留言