可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I'm facing a problem with "distance ValueError: math domain error
" when using sqrt
function in python.
Here is my code:
from math import sqrt def distance(x1,y1,x2,y2): x3 = x2-x1 xFinal = x3^2 y3 = y2-y1 yFinal = y3^2 final = xFinal + yFinal d = sqrt(final) return d
回答1:
Your issue is that exponentiation in Python is done using a ** b
and not a ^ b
(^
is bitwise XOR) which causes final to be a negative value, which causes a domain error.
Your fixed code:
def distance(x1, y1, x2, y2): return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** .5 # to the .5th power equals sqrt
回答2:
The power function in Python is **
, not ^
(which is bit-wise xor). So use x3**2
etc.