I am just experimenting and having fun with Python 2.7 and I'm trying to write a quadratic equation solver. I had it working when the radicand is positive, but when it's negative im getting an error. even after this if else statement. it also doesnt work with big numbers. thanks for the help.
import math
a = raw_input("a = ")
b = raw_input("b = ")
c = raw_input("c = ")
float(a)
float(b)
float(c)
radicand = ((b**2)-4*a*c)
if radicand >= 0:
print(((0-b) + math.sqrt((b**2)-4*a*c))/(2*a))
print(((0-b) - math.sqrt((b**2)-4*a*c))/(2*a))
else:
print "Imaginary Radical"
when i replace (b**2)-4*a*c with radicand i get an invalid syntax error and print is highlighted in red.
the error message says
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
thanks again for any insight you can provide...
You should replace:
float(a)
with:
a = float(a)
and similarly for the other variables.
The statement float(a)
doesn't actually turn a
into a float
, it simply casts it, as per the following transcript:
>>> a = raw_input("a? ")
a? 4.5
>>> type(a)
<type 'str'>
>>> float(a)
4.5
>>> type(a)
<type 'str'>
>>> a = float(a)
>>> type(a)
<type 'float'>
You can see that the type of a
is still str
immediately after performing float(a)
but, when you execute thew assignment a = float(a)
, the type becomes float
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With