Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqrt: ValueError: math domain error

Tags:

python

math

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
like image 218
John Avatar asked Dec 04 '22 09:12

John


2 Answers

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
like image 154
orlp Avatar answered Dec 28 '22 03:12

orlp


The power function in Python is **, not ^ (which is bit-wise xor). So use x3**2 etc.

like image 36
Sven Marnach Avatar answered Dec 28 '22 03:12

Sven Marnach