如何对复数进行四舍五入?

11

如何将一个复数(例如1.9999999999999998-2j)四舍五入为2-2j

当我尝试使用以下代码:

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
你是想要实际改变这个值,还是只是打印一个四舍五入的表示呢? - Zero Piraeus
我想要改变这个值。 - prav
5个回答

11

将实部和虚部分别四舍五入并组合起来:

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

10
如果你只是想以展示的方式表达舍入后的值,而不是修改该值本身,那么以下内容可以达到目的:
>>> x=1.9999999999999998-2j
>>> print("{:g}".format(x))
2-2j

请查看:格式说明迷你语言

要将不是由浮点精度引起的数字四舍五入,例如 2.9+1j,您可以使用小精度格式,如 f"{2.9+1j:.0g}"。请注意,此方法对于小数不起作用:f"{.9+1j:.0g}" = '0.9+1j' - Carl Walsh
你可以使用格式 f 而不是 g 来强制四舍五入小数,例如 f"{.9+1j:.0f}" 可以得到 '1+1j'(我不知道为什么一年前我没有发现这个)。 - Carl Walsh

3
我认为最好的方法是这样做:
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,除非你特别需要,否则不需要输入它们。但是它们很方便。


2

也许你可以为本地使用编写自己的_complex?这是一个例子:

class _complex(complex):
    def __round__(self, n=None):
        try:
            assert isinstance(n, int)
        except AssertionError:
            raise ValueError(f"n must be an integer: {type(n)}")
        if n is not None:
            return complex(round(self.real, n), round(self.imag, n))
        return self

你可以像这样使用它:

c = _complex(1, 2)
print(round(c, 4))

非常粗糙...可能需要一些清理。我很惊讶这不在Python标准库中。


0
你可以单独舍入实部和虚部,而不是将它们合并在一起。例如:
x=complex(1.9999999999999998,-2)
rounded_x=complex(round(x.real,2),round(x.imag,2))

然后您可以将rounded_x变量作为字符串打印出来(以避免在打印时出现括号)。 希望这个简短的答案对包括提问者在内的读者有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接