当前位置:文档之家› 用梯形法或者辛普森法数值积分,分别用Matlab和c语言实现。

用梯形法或者辛普森法数值积分,分别用Matlab和c语言实现。

Matlab作业(一)
作业要求:用梯形法或者辛普森法数值积分,分别用Matlab和c 语言实现。

C语言
1.程序代码:
#include <stdio.h>
#include <math.h>
double fun(double x)
{
return x*x;
}
double definfresult1(double (*pfun)(double),double a,double b,double eps)
{
int n=1;
double h,k,tn,tn1,fh,fh1=0;
double fa=pfun(a);
double fb=pfun(b);
tn=(b-a)*(fa+fb)/2;
do {
for(k=0,fh1=0;k<n;k++){
h=(b-a)/(n);
fh=pfun(a + (2*k + 1)*(b-a)/(2*n));
fh=fh+fh1;
fh1=fh;
}
tn1=tn;
tn=(tn1+fh*h)/2;
n=2*n;
} while(fabs(tn- tn1) >= eps);
return tn;
}
int main()
{
double a,b,eps,definfresult;
printf("积分下限a=");
scanf("%lf",&a);
printf("积分上限b=");
scanf("%lf",&b);
printf("精度eps=");
scanf("%lf",&eps);
definfresult=definfresult1(fun,a,b,eps);
printf("\n计算结果=%.7lf\n", definfresult); }
2.运行结果:
MatLab
1.程序代码:
function y=fun1(x)
y=x*x;
function result=definf1(fhandle, a, b, eps)
fa=feval(fhandle, a);
fb=feval(fhandle, b);
tn=(b-a)*(fa+fb)/2;
tn1=0;
n=1;
fh1=0;
while abs(tn- tn1) > eps
fh1=0;
for i=0:n-1
h=(b-a)/n;
fh=feval(fhandle,a + (2*i + 1)*(b-a)/(2*n) );
fh=fh+fh1;
fh1=fh;
end;
tn1=tn;
tn=(tn1+fh*h)/2;
n=2*n;
end
result=tn;
>> result=definf1(@fun1, 0, 10,0.001 ) result =
333.3335
2.运行结果。

相关主题