Josef Buchko Josef Buchko - 2 months ago 10
Python Question

What is wrong with the following quadratic equation code?

I am trying to make a program that converts standard form quadratic equations to factored form using the quadratic formula, but I'm getting an error on the part where I begin to do math. It seems like it has a problem with the floats I am using, but I do not know why, nor do I know how to fix it.

This is the error I get:

Traceback (most recent call last):
File "C:\Users\Josef\Documents\Python\standardFactored.py", line 25, in <module>
rightS = b^2-4*a*c
TypeError: unsupported operand type(s) for ^: 'float' and 'float'





Here's the code:

print("This program will convert standard form quadratic equations to "
"factored form. ax^2+bx+c --> a(x+ )(x+ )")

while True:
try:
a = float(raw_input("a = "))
break
except:
print("that is not a valid number")

while True:
try:
b = float(raw_input("b = "))
break
except:
print("that is not a valid number")

while True:
try:
c = float(raw_input("c = "))
break
except:
print("that is not a valid number")

rightS = b^2-4*a*c
try:
math.sqrt(rightS)
except:
("There is no factored for for this equation")
quit()

Answer

The ^ operator probably doesn't do what you expect. It's a binary XOR, or eXclusive OR operator. The XOR operator doesn't work with floating point numbers, thus producing the error. The error basically says it can't do the operation on two floats. With exponents, use a double asterisk. See the Python operators here.

Example, a to the power b is:

a ** b

In your case, it would be:

rightS = b ** 2 - 4 * a * c