C语言用辛普森公式求sinx在0到π上的定积分的源程序

如题所述

用梯形法估算,再用辛普森法。
fsimpf 积分函数
a,b 积分下上限,eps 精度。

#include<stdlib.h>
#include <math.h>

double fsimpf(double x)
{
return sin(x) ;
}

double fsimp(double a,double b,double eps)
{
int n,k;
double h,t1,t2,s1,s2,ep,p,x;
n=1; h=b-a;
t1=h*(fsimpf(a)+fsimpf(b))/2.0;
s1=t1;
ep=eps+1.0;
while (ep>=eps)
{
p=0.0;
for (k=0;k<=n-1;k++)
{
x=a+(k+0.5)*h;
p=p+fsimpf(x);
}
t2=(t1+h*p)/2.0;
s2=(4.0*t2-t1)/3.0;
ep=fabs(s2-s1);
t1=t2; s1=s2; n=n+n; h=h/2.0;
}
return(s2);
}
void main()
{
double a,b,eps,t;
a=0.0; b=3.141592653589793238; eps=0.0000001;
a definite integral by Simpson Method.
t=fsimp(a,b,eps);
printf("%e\n",t);
printf("\n Press any key to quit...");
getch();
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2020-01-04
用梯形法估算,再用辛普森法。
fsimpf
积分函数
a,b
积分下上限,eps
精度。
#include<stdlib.h>
#include
<math.h>
double
fsimpf(double
x)
{
return
sin(x)
;
}
double
fsimp(double
a,double
b,double
eps)
{
int
n,k;
double
h,t1,t2,s1,s2,ep,p,x;
n=1;
h=b-a;
t1=h*(fsimpf(a)+fsimpf(b))/2.0;
s1=t1;
ep=eps+1.0;
while
(ep>=eps)
{
p=0.0;
for
(k=0;k<=n-1;k++)
{
x=a+(k+0.5)*h;
p=p+fsimpf(x);
}
t2=(t1+h*p)/2.0;
s2=(4.0*t2-t1)/3.0;
ep=fabs(s2-s1);
t1=t2;
s1=s2;
n=n+n;
h=h/2.0;
}
return(s2);
}
void
main()
{
double
a,b,eps,t;
a=0.0;
b=3.141592653589793238;
eps=0.0000001;
a
definite
integral
by
Simpson
Method.
t=fsimp(a,b,eps);
printf("%e\n",t);
printf("\n
Press
any
key
to
quit...");
getch();
}