【问题标题】:How to round complex number up to 2 decimal points in python?如何在python中将复数四舍五入到小数点后2位?
【发布时间】:2019-08-09 13:42:03
【问题描述】:

我想将复数和实数部分四舍五入到小数点后 2 位。我如何在 python 中做到这一点?

angle = 2 * np.pi *2 
c1 = complex(np.cos(angle),np.sin(angle))
c1 = round(c1,2)

【问题讨论】:

  • 如果您只想显示圆角:f"{c1:.2}""{:.2}".format(c1)
  • complex(round(c1.real,2), round(c1.imag, 2))
  • x = complex(round(x.real,2), round(x.imag,2))
  • 我没有在矩阵中使用这些复数。为了便于阅读,我希望将其显示到小数点后 2 位
  • @Rick .2 将其四舍五入到两位的精度(例如,1.23 被四舍五入为 1.2),而不是两位小数。可以考虑使用.2f

标签: python numpy rounding complex-numbers


【解决方案1】:

您在评论中指出:

我没有在矩阵中使用这些复数。为了便于阅读,我希望将其显示到小数点后 2 位

那么如何修改数据的打印,而不是弄乱它们作为数据的表示?您只需 set_printoptions 使用复数格式化程序:

>>> import numpy as np

>>> arr = np.random.rand(3,3) + 1j*np.random.rand(3,3)
... print(arr)
[[0.44078748+0.29907718j 0.79358223+0.02234568j 0.20919567+0.34527526j]
 [0.05402969+0.24115898j 0.20941358+0.55299497j 0.29743888+0.32179154j]
 [0.60174937+0.9542182j  0.47197093+0.9202769j  0.41205623+0.27288905j]]

>>> np.set_printoptions(formatter={'complex_kind': '{:.2f}'.format})

>>> print(arr)
[[0.44+0.30j 0.79+0.02j 0.21+0.35j]
 [0.05+0.24j 0.21+0.55j 0.30+0.32j]
 [0.60+0.95j 0.47+0.92j 0.41+0.27j]]

【讨论】:

    【解决方案2】:

    我认为你可以使用 numpy 中的around 函数:

    import numpy
    
    x= complex(1.2345, 1.2345)
    numpy.around(x, 2)
    # (1.23+1.23j)
    

    【讨论】:

      【解决方案3】:

      对于紧凑的输出:

      np.set_printoptions(precision=2, suppress=True)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-01-03
        • 1970-01-01
        • 2012-11-07
        • 2015-11-24
        • 2012-03-11
        • 1970-01-01
        • 2012-07-26
        相关资源
        最近更新 更多