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
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
The power function in Python is **
, not ^
(which is bit-wise xor). So use x3**2
etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With