Home > OS >  Python complex number __add__ not working
Python complex number __add__ not working

Time:12-15

I need to make this for python class. So this is the code for overlaping operator for add :

class complex_number :
    def __init__(self, real,imaginary=0.0) :
        self.real = real
        self.imaginery = imaginary
    def __add__ (self, other):
        return complex_number(self.real   other.real,self.imaginery   other.imaginery)
x = complex(2,10j)
y = complex(3,5j)
z = x   y

My problem is that I am getting a wrong result. Im getting (-10,0j) Correct result is (5,15j) Some other info. I found work of other people online and Im still getting the wrong result. addition of complex numbers goes like this : (a bi) (c di) = (a c) (b d)

CodePudding user response:

you assign to x and y standart complex class, not your complex_number.

also writing j is error. What is this j?

this works fine:

class complex_number :
    def __init__(self, real, imaginary=0.0):
        self.real = real
        self.imaginary = imaginary
    def __str__(self):
        return f'{self.real}   {self.imaginary}*i';
    def __add__(self, other):
        return complex_number(self.real   other.real, self.imaginary   other.imaginary)
x = complex_number(2,10)
y = complex_number(3,5)
z = x   y

print(z) // output: 5   15*i

CodePudding user response:

I found the problem by accident.

x = complex(2,10)
y = complex(3, 5)

j is not supposed to be writen.

  • Related