Practical 12
Practical 12
Aim: Write a program to evaluate numerical integration using Trapezoidal rule/ Simpsons one
third rule for the given data
Theory:
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 :
• C++
• Java
• Python3
• C#
• PHP
• Javascript
# Python code for simpson's 1 / 3 rule
import math
# 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 code
lower_limit = 4 # Lower limit
upper_limit = 5.2 # Upper limit
n = 6 # Number of interval
print("%.6f"% simpsons_(lower_limit, upper_limit, n))
Learn Data Structures & Algorithms with GeeksforGeeks
Output:
1.827847
Time Complexity: O(n)
Auxiliary Space: O(1)
Conclusion: