f(x)=y , a=0 b=5.0
n=10
0 0
0.5 4.67
1.0 7.34
1.5 8.86
2.0 9.73
2.5 10.22
3.0 10.51
3.5 10.67
4.0 10.76
4.5 10.81
5.0 10.81
/* based on Simpson's Rule to compute
* definite integral with domain [a,b] and
* n even-grid. n must be even.
*/
#include <stdio.h>
#include <math.h>
#define PI 3.141593
int main()
{
int n,i,m;
double a,b,h ,sum1=0.0,sum2=0.0,sn;
n=10;
a=0;
b=5.0;
double x[11]={ 0, 0.5 , 1.0 , 1.5 , 2.0, 2.5 , 3.0 , 3.5 , 4.0 , 4.5 ,5.0 } ;
double y[11]={ 0,4.67 , 7.34, 8.86, 9.73,10.22 , 10.51,10.67,10.76, 10.81,10.81};
m=n/2;
h=(b-a)/n;
for(i=1;i<=2*m-1;i++)
{
if(i%2==0)
{
sum2=sum2+y[i];
printf("i=%d ,y[%d]=%0.4lf , sum2=%0.4lf ,",i,i,y[i],sum2);
}
else
{
sum1=sum1+y[i];
printf("i=%d ,y[%d]=%0.4lf , sum1=%0.4lf\n",i,i,y[i],sum1);
}
}
sn=(h/3.0)*(y[0]+y[n]+2.0*sum2+4.0*sum1);
printf("\n\nsn=(h/3.0)*(y[0]+y[n]+2.0*sum2+4.0*sum1)\n");
printf("S%d=%lf\n",n,sn);
return 0 ;
}
輸出畫面
i=1 ,y[1]=4.6700 , sum1=4.6700
i=2 ,y[2]=7.3400 , sum2=7.3400 ,i=3 ,y[3]=8.8600 , sum1=13.5300
i=4 ,y[4]=9.7300 , sum2=17.0700 ,i=5 ,y[5]=10.2200 , sum1=23.7500
i=6 ,y[6]=10.5100 , sum2=27.5800 ,i=7 ,y[7]=10.6700 , sum1=34.4200
i=8 ,y[8]=10.7600 , sum2=38.3400 ,i=9 ,y[9]=10.8100 , sum1=45.2300
sn=(h/3.0)*(y[0]+y[n]+2.0*sum2+4.0*sum1)
S10=44.735000
沒有留言:
張貼留言