pythonroundingcomplex-numbers

How to round up a complex number?


How can I round up a complex number (e.g. 1.9999999999999998-2j) as 2-2j?

When I tried using

print(round(x, 2))

it showed

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

That's Python 3.4. I also tried in Python 2 and got TypeError: can't convert complex to float


Solution

  • Round real part and imaginary part separately and combine them:

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