【问题标题】:How to NOT print the j in Python complex numbers?如何不在 Python 复数中打印 j?
【发布时间】:2021-07-30 21:36:23
【问题描述】:

假设其中一个答案应该是 3.00,它将打印为 3.00+0.00j

如何删除 j 并使其仅作为 3.00

#Viete's Algorithm
    def result_2(a3,a2,a0,a1):
        b = b_cof(a3,a2,a1,a0)
        a = a_cof(a3,a2,a1)
        p = P(a3, a2)
        r = -(b / 2.0)
        q = (a / 3.0)
    
        if ((r**2)+(q**3))<= 0.0:
            if q==0:
                theta = 0
            if q<0:
                theta = cmath.acos(r/(-q**(3.0/2.0)))
    
        phi1 = theta / 3.0
        phi2 = phi1 - ((2*cmath.pi) / 3.0)
        phi3 = phi1 + ((2*cmath.pi) / 3.0)
    
        print("X1 = ", "{:.2f}".format(2*math.sqrt(-q)*cmath.cos(phi1)-p/3.0))
        print("X2 = ", "{:.2f}".format(2*math.sqrt(-q)*cmath.cos(phi2)-p/3.0))
        print("X3 = ", "{:.2f}".format(2*math.sqrt(-q)*cmath.cos(phi3)-p/3.0))

【问题讨论】:

    标签: python complex-numbers


    【解决方案1】:

    如果数字为零,你可以去掉虚数部分:

    >>> x=3+0j
    >>> print(f"X1 = {x if x.imag else x.real:.2f}")
    X1 = 3.00
    >>> x=3+1j
    >>> print(f"X1 = {x if x.imag else x.real:.2f}")
    X1 = 3.00+1.00j
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-12
      相关资源
      最近更新 更多