如何整理复数?

时间:2014-09-13 06:05:06

标签: python python-3.x rounding complex-numbers

如何将复数(例如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

5 个答案:

答案 0 :(得分:4)

如果您想要做的只是表示如图所示舍入的值,而不是修改值本身,则以下工作:

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

请参阅:Format Specification Mini-Language

答案 1 :(得分:3)

分别对实部和虚部进行舍入并将它们组合起来:

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

答案 2 :(得分:0)

Id说最好的方法就是这样

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,因此除非特别需要,否则无需输入它们。但是他们很方便

答案 3 :(得分:0)

您可以将实部虚部四舍五入,而不是合并在一起。 喜欢:

x=complex(1.9999999999999998,-2)
rounded_x=complex(round(x.real,2),round(x.imag,2))

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

答案 4 :(得分:0)

好吧,也许您可​​以编写自己的 _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 标准库中。