距离公式上的Python数学域错误

paj*_*ajm 0 python math

在我的代码中:

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

有时,看似随机,我在调用此方法时遇到ValueError:math域错误.有什么问题?谢谢.

ken*_*ytm 15

使用**提高到一个权力,即

    return math.sqrt((vector2[0]-vector1[0])**2+(vector2[1]-vector1[1])**2)
Run Code Online (Sandbox Code Playgroud)

在Python和许多其他C语言中,^代表bitwise-xor,它可能会产生负数,从而导致"数学域错误".

BTW,整个操作可以被计算math.hypot功能.

    return math.hypot(vector2[0]-vector1[0], vector2[1]-vector1[1])
Run Code Online (Sandbox Code Playgroud)

  • `hypot`对于速度(在C代码中完成的所有操作)和准确性(http://en.wikipedia.org/wiki/Hypot)都是优选的. (2认同)