用C语言编写一个求定积分的程序

用C语言编写一个求定积分的程序,第1张

这是辛普森积分法。

给你写了fun_1( ),fun_2(),请自己添加另外几个被积函数。

调用方法 t=fsimp(a,b,eps,fun_i)

a,b --上下限,eps -- 迭代精度要求。

#include<stdio.h>

#include<stdlib.h>

#include <math.h>

double fun_1(double x)

{

return 1.0 + x

}

double fun_2(double x)

{

return 2.0 * x + 3.0

}

double fsimp(double a,double b,double eps, double (*P)(double))

{

int n,k

double h,t1,t2,s1,s2,ep,p,x

n=1h=b-a

t1=h*(P(a)+P(b))/2.0

s1=t1

ep=eps+1.0

while (ep>=eps)

{

p=0.0

for (k=0k<=n-1k++)

{

x=a+(k+0.5)*h

p=p+P(x)

}

t2=(t1+h*p)/2.0

s2=(4.0*t2-t1)/3.0

ep=fabs(s2-s1)

t1=t2s1=s2n=n+nh=h/2.0

}

return(s2)

}

void main()

{

double a,b,eps,t

a=0.0b=3.141592653589793238eps=0.0000001

// a definite integral by Simpson Method.

t=fsimp(a,b,eps,fun_1)

printf("%g\n",t)

t=fsimp(a,b,eps,fun_2)

printf("%g\n",t)

// ...

printf("\n Press any key to quit...")

getch()

}

基本是这样的,用梯形发求定积分,对应于一个积分式就要有一段程序,不过你可以改变程序的一小部分来改变你所要求的积分式。

以c为例:求f(x)=xsinx从1到2的积分

#include <math.h>

float integral(float(*fun)(float x),float a,float b,int,n)

{float s,h,y

int i

s=(fun(a)+fun(b))/2

h=(b-a)/n/*积分步长*/

for(i=1i<ni++)

s=s+fun(a+i*h)

y=s*h

return y/*返回积分值*/

}

float f(float x)

{return(x*sinx) /*修改此处可以改变被积函数*/

}

main()

{float y

y=integral(f,1.0,2.0,150)/*修改此处可以改变积分上下限和步长*/

printf("y=%f\n",y)

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/8127356.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-13
下一篇 2023-04-13

发表评论

登录后才能评论

评论列表(0条)

保存