In this paper, we describe the Simpson method of Python to realize numerical integration. Share to everyone for your reference. Specific as follows:
#coding = Utf-8#simpson method calculates integral, numerical integral, the effect is very ideal from math import *def func (x): "" " defines the integral function" "" Return X*sin (x) def get_n (a,b,w Idth): # Width for step n=int ((b-a)/width + 1) If n%2 = = 0: n=n+1 return Ndef generatedata (a,b,n,width): Datas = [] r=a for I in range (0,n): datas.append (func (R)) r = r+width return datasdef 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] Retur n sum*width/3.0if __name__ = = "__main__": a=1.0 #积分上限 b=3.0 #积分下限 width=0.0625 #步长 n=get_n (a,b,width) datas = Generatedata (a,b,n,width) Print simpson_integral (datas,width,n)
Hopefully this article will help you with Python programming.