SoFunction
Updated on 2024-12-20

Example analysis of python implementation of Simpson's method for numerical integration

This example article describes the Simpson method for implementing numerical integration in python. Shared for your reference. Specifically as follows:

#coding = utf-8
#simpson's method of integrals, numerical integration, works like a charm.
from math import *
def func(x): 
 """
 Define the integrated function
 """
 return x*sin(x)
def Get_N(a,b,width):
 # width is the step size
 N=int((b-a)/width + 1)
 if N%2 == 0:
  N=N+1
 return N
def GenerateData(a,b,n,width):
 datas = []
 r=a
 for i in range(0,n):
  (func(r))
  r = r+width
 return datas
def simpson_integral(datas,width,n):
 sum = datas[0]+datas[n-1]
 for i in range(2,n):
  if i%2== 0:
   sum = sum +4*datas[i-1]
  else:
   sum = sum +2*datas[i-1]
 return sum*width/3.0
if __name__ == "__main__":
 a=1.0 #Points cap
 b=3.0 # Lower limit of points
 width=0.0625 #Steps
 N=Get_N(a,b,width)
 datas = GenerateData(a,b,N,width)
 print simpson_integral(datas,width,N)

I hope that what I have said in this article will help you in your Python programming.