您得到一个复数,因为您在-1
函数中使用了负数2**0.5
升为无理数(dist
):
我编写了这段简短但希望很漂亮的解释性代码,因为在处理基本数学运算时遇到了有趣的意外行为。
from collections import namedtuple
P = namedtuple('P', 'x y')
# euclidean distance with missing parentheses before sqroot
dist = lambda p1, p2:(p1.x-p2.x)**2 + (p1.y-p2.y)**2 ** 0.5
# correct_dist = lambda p1, p2: ((p1.x-p2.x)**2 + (p1.y-p2.y)**2)**0.5
A = P(0, 0)
B = P(1, 1)
AB = dist(A, B)
print(AB, type(AB)) # returns complex?!
print(-1**2 -1**2 **0.5) # -2.0 (as expected since root not applied to the sum)
顺便说一句,这更多是出于理解目的(而不是实际使用)。请帮助我更好地理解这一点!
您错过了一些括号。
(p1.x-p2.x) ** 2 + (p1.y-p2.y) ** 2 ** 0.5
应该是
((p1.x-p2.x) ** 2 + (p1.y-p2.y) ** 2) ** 0.5
然后您将获得预期的1.4142135623730951
(而不是您所写的-2)。
需要括号,因为**
的优先级高于+
。
这是解释此结果的操作顺序:
>>> 2 ** 2 ** 0.5
2.665144142690225
>>> 2 ** (2 ** 0.5)
2.665144142690225
>>> (2 ** 2) ** 0.5
2.0
在您的情况下,您会得到(0 - 1) ** (2 ** 0.5)
,它将无理数(sqrt(2)
)取负数(-1),因此输出为复数。
我们可以看到:
>>> (0 - 1) ** (2 ** 0.5)
(-0.26625534204141565-0.9639025328498773j)
>>> (-1) ** math.sqrt(2)
(-0.26625534204141565-0.9639025328498773j)
Python(**
)中的幂运算符从从右到左]组。从Python Doc (Expressions):
同一框中的运算符从左到右分组(除幂运算,从右到左分组)。>>
顺便说一下,您的台词:
print(-1**2 -1**2 **0.5)
产生-2,因为它等效于:
print(-(1**2) - (1 ** (2 ** 0.5)))
您得到一个复数,因为您在-1
函数中使用了负数2**0.5
升为无理数(dist
):
(-1)**(2**0.5)
您可以在此处阅读更多有关将负数提高为小数或无理数的信息:
您得到一个复数,因为您在-1
函数中使用了负数2**0.5
升为无理数(dist
):