Program for Simpson’s 1/3 Rule

18 Aug, 2021
In numerical analysis, Simpson’s 1/3 rule is a method for numerical approximation of definite integrals. Specifically, it is the following approximation: 
    
In Simpson’s 1/3 Rule, we use parabolas to approximate each part of the curve.We divide the area into n equal segments of width Δx. Simpson’s rule can be derived by approximating the integrand f (x) (in blue) by the quadratic interpolant P(x) (in red).  
In order to integrate any function f(x) in the interval (a, b), follow the steps given below:1.Select a value for n, which is the number of parts the interval is divided into. 2.Calculate the width, h = (b-a)/n 3.Calculate the values of x0 to xn as x0 = a, x1 = x0 + h, .....xn-1 = xn-2 + h, xn = b. Consider y = f(x). Now find the values of y(y0 to yn) for the corresponding x(x0 to xn) values. 4.Substitute all the above found values in the Simpson’s Rule Formula to calculate the integral value.Approximate value of the integral can be given by Simpson’s Rule: 
    
Note : In this rule, n must be EVEN.Application : It is used when it is very difficult to solve the given integral mathematically. This rule gives approximation easily without actually knowing the integration rules.Example :  
Evaluate logx dx within limit 4 to 5.2.

First we will divide interval into six equal 
parts as number of interval should be even.

x    :  4     4.2   4.4   4.6   4.8  5.0  5.2
logx :  1.38  1.43  1.48  1.52  1.56 1.60 1.64

Now we can calculate approximate value of integral
using above formula:
     = h/3[( 1.38 + 1.64) + 4 * (1.43 + 1.52 + 
                      1.60 ) +2 *(1.48 + 1.56)]
     = 1.84
Hence the approximation of above integral is 
1.827 using Simpson's 1/3 rule.  
          
 
C++
Java
Python3
C#
PHP
Javascript
// CPP program for simpson's 1/3 rule#include <iostream>#include <math.h>using namespace std; // Function to calculate f(x)float func(float x){    return log(x);} // Function for approximate integralfloat simpsons_(float ll, float ul, int n){    // Calculating the value of h    float h = (ul - ll) / n;     // Array for storing value of x and f(x)    float x[10], fx[10];     // Calculating values of x and f(x)    for (int i = 0; i <= n; i++) {        x[i] = ll + i * h;        fx[i] = func(x[i]);    }     // Calculating result    float res = 0;    for (int i = 0; i <= n; i++) {        if (i == 0 || i == n)            res += fx[i];        else if (i % 2 != 0)            res += 4 * fx[i];        else            res += 2 * fx[i];    }    res = res * (h / 3);    return res;} // Driver programint main(){    float lower_limit = 4; // Lower limit    float upper_limit = 5.2; // Upper limit    int n = 6; // Number of interval    cout << simpsons_(lower_limit, upper_limit, n);    return 0;}
// Java program for simpson's 1/3 rule public class GfG{     // Function to calculate f(x)    static float func(float x)    {        return (float)Math.log(x);    }     // Function for approximate integral    static float simpsons_(float ll, float ul,                                       int n)    {        // Calculating the value of h        float h = (ul - ll) / n;         // Array for storing value of x        // and f(x)        float[] x = new float[10];        float[] fx= new float[10];         // Calculating values of x and f(x)        for (int i = 0; i <= n; i++) {            x[i] = ll + i * h;            fx[i] = func(x[i]);        }         // Calculating result        float res = 0;        for (int i = 0; i <= n; i++) {            if (i == 0 || i == n)                res += fx[i];            else if (i % 2 != 0)                res += 4 * fx[i];            else                res += 2 * fx[i];        }                 res = res * (h / 3);        return res;    }     // Driver Code    public static void main(String s[])    {          // Lower limit        float lower_limit = 4;                 // Upper limit        float upper_limit = (float)5.2;                 // Number of interval        int n = 6;                 System.out.println(simpsons_(lower_limit,                                upper_limit, n));    }} // This code is contributed by Gitanjali
# Python code for simpson's 1 / 3 ruleimport math # Function to calculate f(x)def func( x ):    return math.log(x) # Function for approximate integraldef simpsons_( ll, ul, n ):     # Calculating the value of h    h = ( ul - ll )/n     # List for storing value of x and f(x)    x = list()    fx = list()         # Calculating values of x and f(x)    i = 0    while i<= n:        x.append(ll + i * h)        fx.append(func(x[i]))        i += 1     # Calculating result    res = 0    i = 0    while i<= n:        if i == 0 or i == n:            res+= fx[i]        elif i % 2 != 0:            res+= 4 * fx[i]        else:            res+= 2 * fx[i]        i+= 1    res = res * (h / 3)    return res     # Driver codelower_limit = 4   # Lower limitupper_limit = 5.2 # Upper limitn = 6 # Number of intervalprint("%.6f"% simpsons_(lower_limit, upper_limit, n))
// C# program for simpson's 1/3 ruleusing System; public class GfG{     // Function to calculate f(x)    static float func(float x)    {        return (float)Math.Log(x);    }     // Function for approximate integral    static float simpsons_(float ll, float ul,                                        int n)    {        // Calculating the value of h        float h = (ul - ll) / n;         // Array for storing value of x        // and f(x)        float[] x = new float[10];        float[] fx= new float[10];         // Calculating values of x and f(x)        for (int i = 0; i <= n; i++) {            x[i] = ll + i * h;            fx[i] = func(x[i]);        }         // Calculating result        float res = 0;        for (int i = 0; i <= n; i++) {            if (i == 0 || i == n)                res += fx[i];            else if (i % 2 != 0)                res += 4 * fx[i];            else                res += 2 * fx[i];        }                 res = res * (h / 3);        return res;    }     // Driver Code    public static void Main()    {        // Lower limit        float lower_limit = 4;                 // Upper limit        float upper_limit = (float)5.2;                 // Number of interval        int n = 6;                 Console.WriteLine(simpsons_(lower_limit,                                upper_limit, n));    }} // This code is contributed by vt_m
<?php// PhP program for simpson's 1/3 rule // Function to calculate f(x)function func($x){    return log($x);} // Function for approximate integralfunction simpsons_($ll, $ul, $n){         // Calculating the value of h    $h = ($ul - $ll) / $n;     // Calculating values of x and f(x)    for ($i = 0; $i <= $n; $i++)    {        $x[$i] = $ll + $i * $h;        $fx[$i] = func($x[$i]);    }     // Calculating result    $res = 0;    for ($i = 0; $i <= $n; $i++)    {        if ($i == 0 || $i == $n)            $res += $fx[$i];        else if ($i % 2 != 0)            $res += 4 * $fx[$i];        else            $res += 2 * $fx[$i];    }         $res = $res * ($h / 3);         return $res;} // Driver program    $lower_limit = 4; // Lower limit    $upper_limit = 5.2; // Upper limit    $n = 6; // Number of interval    echo simpsons_($lower_limit, $upper_limit, $n);     // This code is contributed by ajit.?>
<script> // JavaScriptprogram for simpson's 1/3 rule     // Function to calculate f(x)    function func(x)    {        return Math.log(x);    }       // Function for approximate integral    function simpsons_(ll, ul, n)    {             // Calculating the value of h        let h = (ul - ll) / n;           // Array for storing value of x        // and f(x)        let x = [];        let fx= [];           // Calculating values of x and f(x)        for (let i = 0; i <= n; i++) {            x[i] = ll + i * h;            fx[i] = func(x[i]);        }           // Calculating result        let res = 0;        for (let i = 0; i <= n; i++) {            if (i == 0 || i == n)                res += fx[i];            else if (i % 2 != 0)                res += 4 * fx[i];            else                res += 2 * fx[i];        }                   res = res * (h / 3);        return res;    }     // Driver code                             // Lower limit        let lower_limit = 4;                   // Upper limit        let upper_limit = 5.2;                   // Number of interval        let n = 6;                   document.write(simpsons_(lower_limit,                                upper_limit, n));                 // This code is contributed by code_hunt.</script>
Output:  
1.827847
 
jit_t
code_hunt
sweetyty
Algebra
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Find minimum number of coins that make a given value
Algorithm to solve Rubik's Cube
Minimum number of jumps to reach end
Modulo 10^9+7 (1000000007)
Modulo Operator (%) in C/C++ with Examples
The Knight's tour problem | Backtracking-1
Program for Decimal to Binary Conversion