我有一段代码,用于在脚本中使用梯形规则通过将误差拟合到多项式来查找数值积分中的误差。这段代码抛出浮动除以零错误,我不知道为什么或如何解决它。
有人可以帮我找到答案吗?
def trap(f,a,b,dx,exact):
N = int(numpy.round(float(b-a)/dx))
w=(b-a)/N
sum = f(a)/2.0 + f(b)/2.0
for i in range(1,N):
sum += f(a+i*w)
area = sum * w
errorf = exact-area
# If the error crosses 0, a polynomial approximation
# to the absolute value will go crazy.
return errorf
此替代方法会抛出相同的错误
# alternate way to handle dx not a divisor of b-a
def alt_trap(f,a,b,dx,exact):
N = int(numpy.floor(float(b-a)/dx))
sum = f(a)/2.0 + f(a+N*dx)/2.0
for i in range(1,N):
sum+= f(a+i*dx)
area = sum*dx
# now add one trapezoid between a+Ndx and b
area += 1/2*(b-(a+N*dx))*(f(b)+f(a+N*dx))
errorf = exact-area
return errorf
答案 0 :(得分:1)
dx是唯一可能为0且抛出ZeroDivisionError的参数。 你可以捕获异常并决定做什么或修改输入 - 取决于你的逻辑。
为了提供默认值,只需添加:
dx = dx or 0.0000001 # 0 is false and python is awesome to support this syntax
如果您想尝试并捕获异常(最好请求原谅然后许可)
import sys # At the top
...
try:
N = int(numpy.floor(float(b-a)/dx))
except ZeroDivisionError, e:
print a, b, dx
N = sys.maxint