Value Error: math domain error in Python

sirius_pain picture sirius_pain · May 7, 2014 · Viewed 23.8k times · Source

I'm writing a code to help me solve the Pythagorean theorem in Python. Problem is, I keep getting this one error when I have the code try solving for B.

This is the bit that always gives me problems:

bsqr = (int(c) ** 2) - (int(a) ** 2)
b = int(bsqr) / sqrt(bsqr)

I get this error:

 Traceback (most recent call last):
 File "<pyshell#24>", line 1, in <module> pythag()
 File "C:\Python34\fact.py", line 156, in pythag
 b = int(bsqr) / sqrt(bsqr)
 ValueError: math domain error

What is causing this error, and how can I fix it?

Answer

mgilson picture mgilson · May 7, 2014

It's likely because bsqr is negative and taking the sqrt of a negative number doesn't work too well.

>>> import math
>>> math.sqrt(-1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: math domain error

Check your algebra/inputs. c (the hypoteneuse) should always be bigger than either of the legs (a and b)


Also, side note, you could also get a ZeroDivisionError if you happen to put in values for a and c which are equal (after int truncates them).