我在Python中创建了一个根据梯形规则计算定积分的函数: Trapezoidal rule formula
代码:
from math import ceil
def Trapez_rule(f, a, b, n):
'''Calculates an estimation of a definite integral of a function f(x), between the boundries a, b, by dividing the area to n equal areas'''
sum = (f(a) + f(b)) / 2
for i in range(ceil((b * n))):
sum += f(a + i / n)
sum *= (b - a) / n
return sum
它给出的答案是应该返回的10倍。 我无法找到问题的根源。
答案 0 :(得分:1)
假设:
a=10
b=20
n=5
这些问题是:
for i in range(ceil((b * n))):
sum += f(a + i / n)
i
从0到99
当i = 99然后:
f(a + i / n) => f(10 + 99/5) => f(29)
您使用n false查看下面的post解决方案,因此这应该有效:
def Trapez_rule(f,a,b,n): h =(b-a)/ float(n) sum =(f(a)+ f(b))/ 2.w. 对于范围内的i(1,n-1): 和+ = f(a + i * h) sum * = h 返还金额
答案 1 :(得分:0)
我继续修改你的代码,并将该功能重命名为适合官方风格指南PEP-8。
def trapezium_rule_integral(f, a, b, n):
'''Calculates an estimate of the definite integral of a function f, between
the boundaries a and b, by dividing the area to n equal areas'''
height = (b - a) / n
x = a
ys = []
while x <= b:
ys.append(f(x))
x += height
estimate = 0.5 * height * ( (ys[0] + ys[-1]) + 2 * (sum(ys[1:-1])) )
return estimate