2014-09-13 15 views
2

當我試圖使用如何圍捕複雜無(1.9999999999999998-2j)如(2-2j)在python

print(round(x,2)) 

它顯示

Traceback (most recent call last): 
    File "C:\Python34\FFT.py", line 22, in <module> 
    print(round(x,2)) 
TypeError: type complex doesn't define __round__ method 
+2

您是否想要實際更改值,或者只是打印它的舍入表示形式? – 2014-09-13 06:14:27

+0

我想改變這個值 – prav 2014-09-13 06:53:39

回答

2

圓形實部和虛部單獨並結合他們:

>>> num = 1.9999999999999998-2j 
>>> round(num.real, 2) + round(num.imag, 2) * 1j 
(2-2j) 
3

如果你想要做的是代表四捨五入值示,而不是修改本身的價值,下面的工作:

>>> x=1.9999999999999998-2j 
>>> print("{:g}".format(x)) 
2-2j 

參見:Format Specification Mini-Language