【问题标题】:Python math domain error on distance formula距离公式上的Python数学域错误
【发布时间】:2011-04-22 19:06:04
【问题描述】:

在我的代码中:

class Vector(object):
    @staticmethod
    def distance(vector1, vector2):
        return math.sqrt((vector2[0]-vector1[0])^2+(vector2[1]-vector1[1])^2)

有时,在调用此方法时,我会得到一个 ValueError: math domain error,这似乎是随机的。有什么问题?谢谢。

【问题讨论】:

  • 一个很好的测试论据。
  • 我认为更大的问题是当您没有引发异常时返回的值!
  • @Patrick Moloney:您的矢量世界似乎仅限于整数......在浮点数上尝试的结果可能会给您一个线索:TypeError: unsupported operand type(s) for ^: 'float' and 'int'
  • @Ignacio Vazquez-Abrams:超越“优秀”。这是测试的典型代表。任何人都会认为这段代码“工作”有点令人担忧。
  • @S.Lott:“作品”通常与“不引发异常”混为一谈:-(

标签: python math


【解决方案1】:

Use ** to raise to a power,即

    return math.sqrt((vector2[0]-vector1[0])**2+(vector2[1]-vector1[1])**2)

在 Python 和许多其他 C 派生语言中,^ 代表 bitwise-xor,它可能会创建一个负数,从而导致“数学域错误”。

顺便说一句,整个操作可以用the math.hypot function计算。

    return math.hypot(vector2[0]-vector1[0], vector2[1]-vector1[1])

【讨论】:

【解决方案2】:

我相信您的问题是使用 xor ^ 而不是 pow **...尝试将该行替换为:

   return math.sqrt((vector2[0]-vector1[0])**2+(vector2[1]-vector1[1])**2)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多