HI I'm running a simple program and one component is a quadratic function solver using the quadratic formula. I'm using the cmath module sqrt() method to computate the sqrt of the discriminant and even though the discriminant is positive, it is still returning a complex number. Though when I display the answers in a tkinter label, I use the %.3f for a float but it says it wont accept it because it is a complex number. Is there a complex number placeholder as well?
def quad(a,b,c):
global answers
print a,b,c
disc=b**2
ac4=4*a*c
disc-=ac4
sdisc=sqrt(disc)
b*=-1
a2=a*2
answer=[]
print a
if a!=0:
ans1=(b+sdisc)/a2
ans2=(b-sdisc)/a2
if ans1==ans2:
answer.append(ans1)
print type(ans1)
answers.config(text='%.3f' %ans1)
else:
answer.append(ans1)
answer.append(ans2)
answers.config(text='%.3f , %.3f' %(ans1,ans2))
elif a==0:
answers.config(text='Not a Quadratic Function.')
it is returning complex number if a is 1 and b,c=0,0... Does cmath return complex numbers no matter what??
Familiar with python though new to complex numbers and just started learning them.
EDIT: I'm now using the math module and special case negative inputs, though when I use %.3f it won't allow me to because it is complex. (I did the sqrt of the negative of the negative number to get the positive sqrt and multiplied that by 1j) is there a placeholder to do this? (like %c??) Thanks
If you expect that the number should be real, you can test it and convert it:
where you should replace 1e-9 with whatever small value suits your problem and the inherent slop of floating point arithmetic.