You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
25 lines
779 B
25 lines
779 B
def trapezoidal_rule(a, b, n):
|
|
"""
|
|
梯形法进行数值积分
|
|
|
|
参数:
|
|
- f: 要积分的函数
|
|
- a: 积分区间的起始点
|
|
- b: 积分区间的结束点
|
|
- n: 划分的子区间数
|
|
|
|
返回:
|
|
- 积分近似值
|
|
"""
|
|
h = (b - a) / n # 子区间宽度
|
|
x = [a + i * h for i in range(n+1)] # 子区间的节点
|
|
y = [x_i ** 2 for x_i in x] # 子区间节点对应的函数值
|
|
integral = (h / 2) * (y[0] + 2 * sum(y[1:n]) + y[n]) # 梯形法计算积分值
|
|
return integral
|
|
|
|
if __name__ == '__main__':
|
|
a = 0 # 积分区间的起始点
|
|
b = 1 # 积分区间的结束点
|
|
n = 100 # 划分的子区间数
|
|
integral = trapezoidal_rule(a, b, n)
|
|
print("数值积分的近似值:", integral) |