Sqrt: ValueError: math error

I am having a problem with distance ValueError: math domain error "when using the 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 
+4
source share
2 answers

Your problem is that exponentiality in Python is done using a ** b , not a ^ b ( ^ is a bitwise XOR), which makes final 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 
+11
source

The power function in Python ** , not ^ (bitwise xor). So use x3**2 etc.

+6
source

Source: https://habr.com/ru/post/1336136/


All Articles