0

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

4
Contributors
6
Replies
8
Views
6 Years
Discussion Span
Last Post by Gribouillis
1

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 ?

Edited by Gribouillis: n/a

0

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

Edited by matthewkeating: n/a

1

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.

Edited by Gribouillis: n/a

Votes + Comments
good source
1

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

0

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

Edited by nathan_czh

0

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 !

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.