我想显示数字,这样如果数字是实数,则只显示实部。 (不要显示
0j
)代码输出为:
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
但我想要这样的东西:
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
有没有简单的方法可以做到这一点?
代码如下。
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))
您可以继承
complex
类型:
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)
这个怎么样,
dist = 3.98+0.00j
print(np.real_if_close(dist))
# 3.98
dist = -2.99j
print(np.real_if_close(dist))
# (-0-2.99j)
以上是默认的
tol=100
,可以在https://numpy.org/devdocs/reference/ generated/numpy.real_if_close.html阅读更多相关信息。