Domain error with square roots
<p>I am trying to copy a code from the book I am learning from. The program is supposed to find the square roots of a quadratic function but once I run the module in IDLE I get an error.</p>

<pre><code>#This is a program to find the square roots of a quadratic function.



import math

def main():

    print ("this is a program to find square roots of a quadratic function")
    print()
    a,b,c = eval(input("enter the value of the coefficients respectively"))

    discRoot = math.sqrt( b * b - 4 * a * c )

    root1 = ( - b + discRoot ) / 2 * a 
    root2 = ( - b - discRoot ) / 2 * a

    print ("The square roots of the equation are : ", root1, root2 )
    print()

main()
</code></pre>

<p>I am getting the following error :</p>

<pre><code>Traceback (most recent call last):
File "/home/ubuntu/Desktop/untitled.py", line 21, in &lt;module&gt;
main()
File "/home/ubuntu/Desktop/untitled.py", line 13, in main
discRoot = math.sqrt( b * b - 4 * a * c )
ValueError: math domain error
</code></pre>

<p>What exactly am I doing wrong here ? Is it because the discRoor value is turning out to be negative ? </p>

<p>I'm guessing you're taking the square root of a negative number which is not in the domain of the <code>math.sqrt</code> function. It will raise a <code>ValueError</code>. You can get rid of this just by checking the discriminant. The discriminant is the bit inside the root. If it is negative, there are no solutions. If it is 0, one solution. If it is positive, then continue solving:</p>

<pre><code>discriminant = b * b - 4 * a * c

if discriminant &lt; 0:
    print("No solution")
elif discriminant == 0:
    root1 = (-b) / 2 * a
    #do stuff
else:
    discRoot = math.sqrt(b * b - 4 * a * c)

    root1 = (-b + discRoot) / 2 * a 
    root2 = (-b - discRoot) / 2 * a
    # do stuff with roots
</code></pre>

python python-3.x