Files
CalWay_Python/按方法整理/数值积分-复合梯形-复合辛普生法.py
2025-06-16 20:44:29 +08:00

39 lines
1.5 KiB
Python
Raw Permalink 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.

# 复合Newton-Cotes公式 复合牛顿-柯特斯公式
# n等分参数x1到x2的区间type=1表示梯形法type=2表示辛普生法
def CompositeNewtonCotes(x_start,x_end,fx,n, type):
if type == 1:
h = (x_end - x_start) / n
result = 0
for i in range(n):
result += (fx(x_start + i * h) + fx(x_start + (i + 1) * h))
result *= (h / 2)
return result
elif type == 2:
h = (x_end - x_start) / n
result = -fx(x_start) + fx(x_end)
for i in range(n):
result += (4 * fx(x_start + (i + 0.5) * h) + 2 * fx(x_start + i * h))
result *= (h / 6)
return result
# 积分原函数 ##############################################################
def fx(x):
if x == 0:
x = 1e-10 # Avoid division by zero #如果x能为0注释掉这行##############
pass
return x/(4+x**2) #把函数改成题干的形式###################
if __name__ == "__main__":
##############################################################################################################
x_start = 3.0 # 积分下限
x_end = 6.0 # 积分上限
# 复合梯形公式点数为n+1
print("复合梯形公式\n", CompositeNewtonCotes(x_start,x_end,fx,8, 1)) #8等分1代表是梯形公式####################
# 复合辛普生公式点数为2n+1
print("复合辛普生公式\n", CompositeNewtonCotes(x_start,x_end,fx,4, 2)) #4等分2代表是辛普生公式###############