Search code examples
pythoncomplex-numbers

How do not show imaginary part (0j) if the number is real in Python?


I would like to display numbers, such that if the number is real only the real part is displayed. (don't show the 0j)
If it is imaginary, so show only the imaginary part. If it is complex, so show the real and the imaginary part.

The code output is:

k = 251.50+0.00j  
fc0 = 0.00 GHz, beta_n0 = 251.50+0.00j, dist = 3.98+0.00j mm  
fc1 = 9.99 GHz, beta_n1 = 139.24+0.00j, dist = 7.18+0.00j mm  
fc2 = 19.99 GHz, beta_n2 = 0.00+334.97j, dist = 0.00-2.99j mm  
fc3 = 29.98 GHz, beta_n3 = 0.00+575.79j, dist = 0.00-1.74j mm  

But I want something like this:

k = 251.50  
fc0 = 0.00 GHz, beta_n0 = 251.50, dist = 3.98 mm  
fc1 = 9.99 GHz, beta_n1 = 139.24, dist = 7.18 mm  
fc2 = 19.99 GHz, beta_n2 = 334.97j, dist = -2.99j mm  
fc3 = 29.98 GHz, beta_n3 = 575.79j, dist = -1.74j mm 

Is there a simple way to do this?

The code is below.

import numpy as np
from scipy.constants import c, mu_0, epsilon_0, pi
from cmath import sqrt

c0 = c
eps0 = epsilon_0
mi0 = mu_0

d = 1.5e-2
f = 12e9
eps_r_ = 1
eps_r__ = 0  #2e-3
mi_r = 1

cc = c0/sqrt(eps_r_*mi_r)
k = 2*pi*f/cc

print("k = {0:.2f}".format(k))

for n in range(4):
    fc = n*c0/(2*d)
    beta_n = sqrt((k**2-(n*pi/d)**2))
    print("fc{0} = {1:.2f} GHz, beta_n{0} = {2:.2f}, dist = {3:.2f} mm".format(n,fc*1e-9,beta_n,1/beta_n*1e3))

Solution

  • You can inherit from the complex type:

    In [1]: class MyComplex(complex):
       ...:     def __repr__(self):
       ...:         if self.imag == 0:
       ...:             return str(self.real)
       ...:         elif self.real == 0:
       ...:             return str(self.imag) + 'j'
       ...:         else:
       ...:             return super(MyComplex, self).__repr__()
       ...:
    In [2]: MyComplex(0)
    Out[2]: 0.0
    
    In [3]: MyComplex(0+0j)
    Out[3]: 0.0
    
    In [4]: MyComplex(1+0j)
    Out[4]: 1.0
    
    In [5]: MyComplex(1j)
    Out[5]: 1.0j
    
    In [6]: MyComplex(1+1j)
    Out[6]: (1+1j)