用分步长的Simpson算法计算积分
可以指定误差eps,如要修改函数则修改fun(x)
from sympy import *
import math
def fun(x):
return cos(x)
def inte_ran_step(fun,u_lim,l_lim,eps):
state = 1
N = 2
while state:
step_length = (u_lim - l_lim) / N
S1 = 0
T1 = 0
T2 = 0
for i in range(N + 1):
if i == 0 or i == N:
S1 += (fun(l_lim + step_length*i))/2 * step_length
else:
S1 += (fun(l_lim + step_length*i)) * step_length
S2 = S1/2
for i in range(N):
S2 += step_length/2 * fun(l_lim + (i + 1/2) * step_length)
S4 = S2/2
for i in range(N):
S4 += step_length/2 * fun(l_lim + (i + 1/2) * step_length)
T1 = 4/3 * S2 -1/3 * S1
T2 = 4/3 * S4 - 1/3 * S2
if abs(T2 - T1) < eps:
print('The accurte integrate is ' + str(T1))
print('N = ' + str(N))
state = 0
else:
N += 2
if __name__ == '__main__':
u_lim = float(input('input upper limit:'))
l_lim = float(input('input lower limit:'))
eps = float(input('input eps:'))
inte_ran_step(fun,u_lim,l_lim,eps)