Home python Math domain error (Python) when calculating sqrt

Math domain error (Python) when calculating sqrt

Author

Date

Category

When testing or checking a function, a message appears stating that the line

root2 = (-b + sqrt (discriminant)) / (2 * a)

passes math domain error. What’s the catch? Thanks in advance


Answer 1, authority 100%

For real numbers, the root of a negative number does not exist:

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

For complex numbers, the root is:

& gt; & gt; & gt; import cmath
& gt; & gt; & gt; cmath.sqrt (-1)
1j

Answer 2

You are taking the square root of a negative number.
Here is the result of running your code on the site (I also pasted print (‘discriminant:’, discriminant))
https://repl.it/FKpS/1

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions