def complex_round(complex_number): real = round(complex_number.real) imag = round(complex_number.imag) return complex(real, imag)It would be nice, to round a complex directly, but this is not implemented in the built-in
complex
.I guess it's mathematically not right to round a complex number.
But you can make a class and add the __round__ method.
class Complex(complex): def __round__(self, digits=0): return complex(round(self.real, digits), round(self.imag, digits))Using this piece of code:
try: # trying first the built-in type complex round(complex(1.5, 3.5)) except TypeError as e: print(e) c = Complex(42.1337, 1337.42) print(round(c))
Output:type complex doesn't define __round__ method
(42+1337j)
By the way, I use complex numbers in real world applications.If you dive into signal processing, you have to handle them, but rounding happens never.
If you have for example a signal, which could be just In-phase or a complex signal,
where the In-phase is the real part and the Quadrature is the imaginary part.
Doing a fft, results again into complex numbers.
To get the magnitude, you could use abs(), which is sqrt(i**2 + q**2), only positive numbers.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!