矩形法

C 语言代码

#include <stdio.h>#include <math.h>double f(double x){
   return sin(x);
   /*也可以回传其他数学子程序,像cos(2*x)或2*atan(3*x+1)-1*/}double rectangle_integrate(double a, double b, int subintervals){
   double result;
   double interval;
   int i;
   
   interval=(b-a)/subintervals;
   result=0;
   
   for(i=1;i<=subintervals;i++){
      result+=f(a+interval*(i-0.5));
   }
   result*=interval;

   return result;}int main(void){
   double integral;
   integral=rectangle_integrate(0,2,100);
   printf("Integral: %f \n",integral);
   return 0;}

Fortran 语言代码

Program Calc

      Double Precision f,y,a,b,J,mult,sum,c1,c2
      Sum=0.0
      c2=0.0
      c1=0.0

      Print*,'Enter the start and end of the interval'
      Read*,a,b
      If (b.gt.a) then         goto 1
      Else         goto 2
      End If        1   Do J=a,b,.00000001
         c1=J
         Y=F(((c1+c2)/2))
         Mult=Y*.00000001
         Sum=sum+mult
         c2=c1
      End Do  2   Do J=a,b,-.00000001
         c1=J
         Y=F(((c1+c2)/2))
         Mult=Y*.00000001
         Sum=sum+mult
         c2=c1
      End Do      Print*,Sum  3   Format (F20.5)
      End      Double Precision Function f(x)
      Double Precision x

      F=(4)/((x**2)+1)

      Return      End