numint.jpg
where
h = ba

2n
.
Note that the number of partitioning for the Simpson rule must be an even number (=2n).
For the coding purpose, it is convenient to write eq.(12) as

I
=
h

3

f0+f2n
+
h

3
×4
f1 + f3 + f5 + …+f2n−1
+
h

3
×2
f2+f4+ f6 + …+ f2n−2
.
(13)
Implementation
  1. C code
    /* Simpson's rule */
    #include <stdio.h>
    #include <math.h>
    
    double f(double x)
     {return 4.0/(1.0+x*x);}
    
    /*
    Note that the number of partitions is 2n, not n.
    */
    int main()
    {
     int i, n ;
     double a=0.0, b=1.0 , h, s1=0.0, s2=0.0, s3=0.0, x;
    
    /* printf("Enter \"n\" (a half of the partitions)  = ");
     scanf("%d", &n) ;
    */
      n=5;
    
      h = (b-a)/(2.0*n) ;
    
      s1 = (f(a)+ f(b));
    
     for (i=1; i<2*n; i=i+2) s2 = s2 + f(a + i*h);
    
     for (i=2; i<2*n; i=i+2) s3 = s3 + f(a + i*h);
    
        printf("The number of partitins is %d.\n", 2*n);
        printf("%20.12f\n", (h/3.0)*(s1+ 4.0*s2 + 2.0*s3)) ;
     return 0;
    }
    
    Online C compiler
    Online C compiler(alternative)
  2. MATLAB (Octave) code
    f = @(x) 4/(1+x^2);
    a=0;b=1;s1=0; s2=0;s3=0;
    n=5;
    %n=input('Enter n= (must be even)');
    
    h=(b-a)/(2*n);
    
    s1=(f(a)+f(b));
    
    for i=1:2:2*n-1  s2=s2+f(a+i*h); end;
    
    for i=2:2:2*n-1 s3=s3+f(a+i*h) ; end;
    
    s= (h/3)*(s1+4*s2+2*s3);
    fprintf('%f\n', s);
    
    Online Octave (Matlab)
According to error analysis, the truncation error for each rule is as follows:
where h is the step size and ξ is a value within the interval.

Computation of π



1

0 
1

1+x2
dx = π

4
.
1overx2plus1.jpg


1

0 


 

1−x2
 
dx = π

4
.
sqrt1minusx2.jpg
It is important to know that the accuracy of numerical integration generally depends on the derivatives of the function, f(x), to be integrated. Although the two examples above yield approximation to π, the convergence speed (and accuracy) varies greatly.



File translated from TEX by TTH, version 4.03.
On 30 Aug 2022, 22:05.