Files
CalWay_Python/120-3.py
2025-06-14 09:26:42 +08:00

33 lines
1.0 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.

#把范围与原函数换成题干的############
x1, x2 = 3, 6
def fx(x):
return x/(4+x**2)
# 复合Newton-Cotes公式 复合牛顿-柯特斯公式
# n等分参数x1到x2的区间type=1表示梯形法type=2表示辛普生法
def CompositeNewtonCotes(n, type):
if type == 1:
h = (x2 - x1) / n
result = 0
for i in range(n):
result += (fx(x1 + i * h) + fx(x1 + (i + 1) * h))
result *= (h / 2)
return result
elif type == 2:
h = (x2 - x1) / n
result = -fx(x1) + fx(x2)
for i in range(n):
result += (4 * fx(x1 + (i + 0.5) * h) + 2 * fx(x1 + i * h))
result *= (h / 6)
return result
if __name__ == "__main__":
# 复合梯形公式点数为n+1
print("复合梯形公式\n", CompositeNewtonCotes(8, 1)) #8等分1代表是梯形公式####################
# 复合辛普生公式点数为2n+1
print("复合辛普生公式\n", CompositeNewtonCotes(4, 2)) #4等分2代表是辛普生公式###############