Placeholders in python String Concatenation

1.2k views Asked by At

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

3

There are 3 answers

0
John1024 On
r = cmath.sqrt(1)
print('%f+i%f' % (r.real, r.imag))

If you expect that the number should be real, you can test it and convert it:

if abs(r.imag) < 1e-9:
    r = r.real
else:
    print('Surprise: got a nonzero imaginary part!')

where you should replace 1e-9 with whatever small value suits your problem and the inherent slop of floating point arithmetic.

0
loopbackbee On

There's multiple possible solutions.

Firstly, you could just use math instead of cmath. It won't adversely impact the performace of the program in any noticeable way.

Otherwise, if you know the number is real, you can just use complex.real: cmath.sqrt(2).real

3
user2357112 On

Does cmath return complex numbers no matter what??

Yes. You'll need to either print complex numbers properly, or use the regular math.sqrt and special-case negative inputs.