《用梯形法或者辛普森法数值积分分别用Matlab和c语言实现》由会员分享,可在线阅读,更多相关《用梯形法或者辛普森法数值积分分别用Matlab和c语言实现(5页珍藏版)》请在金锄头文库上搜索。
1、Matlab作业(一)作业要求:用梯形法或者辛普森法数值积分,分别用Matlab和c语言实现。C语言1. 程序代码:#include #include 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= eps);retu
2、rn 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计算结果=%.7lfn, definfresult);2.运行结果:MatLab1. 程序代码:function y=fun1(x) y=x*x; function result=definf1(fhandle, a, b, eps)
3、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.33352.运行结果