# how to complex numbers in python?

class complex_number:
def _init_(self, n):
self.n = n

if isinstance(other, int):
return complex_number(self.n + other)
elif isinstance(other, complex_number):
return complex_number(self.n + other.n)
else:
raise TypeError

def __truediv__(self, other):
if isinstance(other, int):
return complex_number(self.n, other)
elif isinstance(other, complex_number):
return complex_number(self.n, other.n)
else:
raise TypeError

def __float__(self):
return float(self.n) / self.n

def __int__(self):
return self.n / self.n

def __mul__(self, other):
if isinstance(other, int):
return complex_number(self.n * other)
elif isinstance(other, complex_number):
return complex_number(self.n * other.n)
else:
raise TypeError

return self + other

def __rtruediv__(self, other):
return complex_number(other) / self

def __rmul__(self, other):
return self * other

def __rsub__(self, other):
return complex_number(other) - self

def __str__(self):
return str(self.n)

def __sub__(self, other):
if isinstance(other, int):
return complex_number(self.n - other)
elif isinstance(other, complex_number):
return complex_number(self.n - other.n)
else:
raise TypeError

if __name__ == '__main__':

a = 3
c = 5
b = 2
d = 1

print('%s + %s = %s' % (a, b, c, d, (3 + 2j) + (5 + 1j)))
print('%s - %s = %s' % (a, b, c, d, (3 + 2j) - (5 + 1j)))
print('%s * %s = %s' % (a, b, c, d, (3 + 2j) * (5 + 1j)))
print('%s / %s = %s' % (a, b, c, d, (3 + 2j) / (5 + 1j)))

answered Aug 6 by (32,880 points)
edited Aug 6 by Peter Minarik

Your print lines at the end of your code make no sense to me.

I'd recommend using string formatting.

I've done a bit of experimenting and it seems like Python has complex numbers as language elements. So I don't see why you need to create your own class for this purpose.

For instance, you could test Python's complex multiplication like this (and yes, it provides the correct result):

`print('{} + {} = {}'.format((3 + 2j), (5 + 1j), (3 + 2j) * (5 + 1j)))`
commented Aug 6 by (1,440 points)
okay, I got  it. Thanks. But how about doing complex numbers  in java? I am confused.
https://onlinegdb.com/1ugVOprTd