Files
CalWay_Python/按方法整理/数值积分-逐次分半梯形递推公式.py
2025-06-16 20:44:29 +08:00

39 lines
1.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import math
# 逐次分半梯形递推公式
def SplitTrapezoidal(a,b,fx,err):
count = 1
t1 = (b-a)*(fx(a)+fx(b))/2
print(f"t{count}={t1}")
k = 1
while True:
tmp = 0
for i in range(1, 2**(k-1)+1):
tmp += fx(a + (b-a)*(2*i-1)/(2**k))
t2 = t1/2+(b-a)*tmp/(2**k)
count *= 2
print(f"t{count}={t2}")
if abs(t2-t1) < err:
break
t1 = t2
k += 1
return t2,k
# 积分原函数 ##############################################################
def fx(x):
if x == 0:
x = 1e-10 # Avoid division by zero #如果x能为0注释掉这行##############
pass
return 1/x #把函数改成题干的形式###################
if __name__ == "__main__":
##############################################################################################################
x_start = 1 # 积分下限
x_end = 3 # 积分上限
err = 1e-2 # 精度要求 P106
result,k = SplitTrapezoidal(x_start, x_end, fx, err)
print(f"Result: {result},k={k}")