I am writing a script that solves a Quadratic equation. What I am doing wrong and why? The error I get is:

Traceback (most recent call last):
File "/home/matthew/Desktop/QuadraticSolver.py", line 5, in <module>
c1 = (b * -1) + math.sqrt(((b*b) - 4*a*c) / 2*a)
ValueError: math domain error

Here is the code:

import math
a = input("Please enter A: ")
b = input("Please enter B: ")
c = input("Please enter C: ")
c1 = (b * -1) + (math.sqrt(((b*b) - 4*a*c) / 2*a))
c2 = (b * -1) - (math.sqrt(((b*b) - 4*a*c) / 2*a))
print c1
print c2

Thanks
Matthew

Perhaps you're taking the square root of a negative number ? Also your formulas are false. Why not introduce a variable delta = b * b - 4 * a * c to clean up the code ?

What do you mean? I first find the square root and then divide by 4ac. However I will fix the negative square root.

What do you mean? I first find the square root and then divide by 4ac. However I will fix the negative square root.

See here http://en.wikipedia.org/wiki/Quadratic_equation#Quadratic_formula :) and compare with your code.
Numerical analysis works like mathematics: when you divide by a number, there is a risk that the number is zero, when you take a square root or a logarithm, there is a risk that the argument is negative. All these cases must be handled by tests.

commented: good source +10

Or you should move to the complex numbers domain as Python supports that. See module cmath.

sqrt cannot handle negative numbers, thus the error.
If you get a negative number, obiously something is wrong with the inputs

sqrt cannot handle negative numbers, thus the error.
If you get a negative number, obiously something is wrong with the inputs

This is an old thread, matthewkeating probably found the solution since he wrote this program. Please answer recent threads, or create new ones !

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.