Reputation: 23
So I am quite a novice at coding python, so I decided to try my hand at making a quadratic equation solver. After entering all my user inputted variables i get this error:
Traceback (most recent call last):
File "C:/Users/insertnamehere/Desktop/quadratic formula solver.py", line 6, in <module>
root=math.sqrt((b**2)-4*a*c)
ValueError: math domain error
My code is:
import math
a=float(input("A?: "))
b=float(input("B?: "))
c=float(input("C?: "))
root=math.sqrt((b**2)-4*a*c)
x=(-b+root)/2*a
x2=(-b-root)/2*a
print(x)
print(x2)
Any help would be appreciated a lot.
Edit: Forgot to add the actual values i entered.
A?: 6
B?: 1
C?: 2
Upvotes: 2
Views: 1739
Reputation: 55469
Python can handle complex numbers, but the math
module won't do square roots of negative numbers, for that you need to use cmath.
Demo:
#!/usr/bin/env python
import cmath
a = 1.0
b = 1.0
c = 1.0
root = cmath.sqrt(b * b - 4.0 * a * c)
x1 = (-b + root) / (2.0 * a)
x2 = (-b - root) / (2.0 * a)
print x1
print x2
output
(-0.5+0.866025403784j)
(-0.5-0.866025403784j)
Although i
is commonly used by mathematicians as the symbol for the square root of negative one, Python uses j
; that convention is common among electronics engineers, since they use i
to represent current.
So the above output is equal to (-1 ± sqrt(-3))/2
Upvotes: 3
Reputation: 36346
That is a basic 9th grad math question:
Quadratic equations don't always have real-valued solutions, because you can't take the square root of a negative number. You've entered values for a quadratic equation that simply can't be solved within the real numbers.
EDIT: you posted your values:
so, what is the square root of (1² - 2*6*2) ? You cannot find a solution in the real numbers to that question, and neither can python, that's why it's giving you a math domain error.
Look at it this way: 6x² + x + 2 = 0 really has no real solution. Hint: Look at the graph
Upvotes: 1