Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 517
prav Avatar asked Sep 13 '14 06:09

prav


3 Answers

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)
like image 169
falsetru Avatar answered Sep 28 '22 18:09

falsetru


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

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

See: Format Specification Mini-Language.

like image 38
Zero Piraeus Avatar answered Sep 28 '22 17:09

Zero Piraeus


Id say the best way to do it is as such

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

if you don't want to repeat that every time you want to do it, you could put it in a function.

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

Additional optional arguments can then be added to this, so if you only want to round one part for example, or if you only want to round to a certain number of decimal places on either 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))

as the variables are auto set to true or 0, you don't need to input them unless you specifically want too. But they are handy to have

like image 40
Evelyn Avatar answered Sep 28 '22 16:09

Evelyn