Frage

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?

War es hilfreich?

Lösung

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).

Andere Tipps

Please go through this:

Square roots in python

Also see the cmath module in Python

cmath module - sqrt

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top