【问题标题】:Identifying and repairing float divide by zero errors (Python)识别和修复浮点除以零错误(Python)
【发布时间】:2016-11-04 05:23:55
【问题描述】:

我有一段代码打算在脚本中使用,通过将错误拟合到多项式来使用梯形规则查找数值积分中的错误。这段代码抛出浮点除以零错误,我不明白为什么或如何解决它。

有人可以帮我找到答案吗?

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

【问题讨论】:

  • if dx == 0:dx = 1e-8 ... 可能会做你想做的事......基本上你不能除以零,所以你必须定义你期望在这种情况下发生的事情......
  • 哦,哇,现在你指出来了,这很明显。谢谢!

标签: python divide-by-zero numerical-integration


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多