John
John

Reputation: 181

sqrt: ValueError: math domain error

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

Upvotes: 4

Views: 26305

Answers (2)

orlp
orlp

Reputation: 118016

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

Upvotes: 11

Sven Marnach
Sven Marnach

Reputation: 602775

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

Upvotes: 6

Related Questions