Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Complex Integer
#4
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!
Reply


Messages In This Thread
Complex Integer - by saumyagoel - Feb-19-2019, 06:43 PM
RE: Complex Integer - by micseydel - Feb-19-2019, 07:49 PM
RE: Complex Integer - by scidam - Feb-20-2019, 12:01 AM
RE: Complex Integer - by DeaD_EyE - Jun-14-2019, 10:52 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020