我认为最好的方法是这样做:
x = (1.542334+32.5322j)
x = complex(round(x.real),round(x.imag))
如果你不想每次都重复这个操作,可以将其放在一个函数中。
def round_complex(x):
return complex(round(x.real),round(x.imag))
还可以添加其他可选参数,例如,如果您只想舍入一个部分,或者只想在实数部分或复数部分中舍入到某个小数位数
def round_complex(x, PlacesReal = 0, PlacesImag = 0, RoundImag = True, RoundReal = True):
if RoundImag and not RoundReal:
return complex(x.real,round(x.imag,PlacesImag))
elif RoundReal and not RoundImag:
return complex(round(x.real,PlacesReal),x.imag)
else: #it would be a waste of space to make it do nothing if you set both to false, so it instead does what it would if both were true
return complex(round(x.real,PlacesReal),round(x.imag,PlacesImag))
由于变量会自动设为true或0,除非你特别需要,否则不需要输入它们。但是它们很方便。