编一个C语言程序--求f(x)在a,b上的定积分

来源:百度知道 编辑:UC知道 时间:2024/06/16 00:11:14

//---------------------------------------------------------------------------

#include <stdio.h>
#include <math.h>

double f(double x)
{
double y;
y=log(x); /*f(x)的定义,可自行修改*/
return y;
}
double simp(double a,double b,const double eps,double (*f)(double))
/*利用simpson公式求f(x)的定积分*/
{
int n=1,k;
double h,t1,t2,s1,s2,ep,p,x;
if (a-b>0) {
x=a;
a=b;
b=x;
}
h=b-a;
t1=h*((*f)(a)+(*f)(b))/2.0;
s1=t1;
ep=eps+1.0;
while (ep>=eps)
{
p=0.0;
for (k=0; k<n; k++) {
x=a+(k+0.5)*h;
p+=(*f)(x);
}
t2=(t1+h*p)/2.0;
s2=(4.0*t2-t1)/3.0;
ep=fabs(s2-s1);
t1=t2;
s1=s2;
n+=n;
h/=2.0;
}
return s2;

}

int main(int argc, char* argv[])
{
printf("%e",simp(1,2,1e-6,f));
return 0;
}