怎样编写c语言积分函数

怎样编写c语言积分函数,第1张

积分分为两种,数值积分,公式积分。

公式积分:部分函数可以直接用公式求得其不定积分函数。C语言中可以直接用积分公式写出其积分函数。

数值积分:按照积分的定义,设置积分范围的步长,用梯形面积累加求得其积分。

以【f(x)=x*sin(x) 从1到2的积分】为例:

#include <math.h>

#include <stdio.h>

double integral(double(*fun)(double x),double a,double b,int,n){

   double 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/*返回积分值*/

}

double f(double x){

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

}

int main(){

   double y

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

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

   return 0

}

这是辛普森积分法。

给你写了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()

}


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

原文地址:https://54852.com/yw/12066233.html

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

发表评论

登录后才能评论

评论列表(0条)

    保存