How to round up a complex number?

How can a complex number (for example 1.9999999999999998-2j

) be rounded up to 2-2j


When I tried to use



it showed

Traceback (most recent call last):
  File "C:\Python34\", line 22, in <module>
TypeError: type complex doesn't define __round__ method



source to share

3 answers

Split real part and imaginary part separately and combine them:

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




If all you want to do is the value rounded as shown, rather than changing the value itself, the following works:

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


See: Mini-Language Specification Format .



I would say the best way to do this is as such

x = (1.542334+32.5322j)
x = complex(round(x.real),round(x.imag))


if you don't want to repeat this every time you want, you can put this in a function.

def round_complex(x):
    return complex(round(x.real),round(x.imag))


Additional optional arguments can be added to this, for example if you only want to round one part, for example, or if you want to round to a certain number of decimal places in the real or complex part

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))


since variables are automatically set to true or 0, you don't need to type them in if you don't want to. But it's convenient to have them



All Articles