Search code examples
pythonpython-3.xadditionsubtractioncomplex-numbers

Python Real and imaginary : How to print -2-2i


Can you please help me with the below code where I am not getting the desired result:

class comp:
  
    def __init__(self, real, imag):
        self.real=real
        self.imag=imag

    def add(self,other):
        print('Sum of the two Complex numbers :{}+{}i'.format(self.real+other.real,self.imag+other.imag))
    
    def sub(self, other):
        print('Subtraction of the two Complex numbers :{}+{}i'.format(self.real-other.real, self.imag-other.imag))

The code works but when the imaginary field takes a result in -2, I know it will print the result as +-2i

Result eg: 1+2i - 3+4i = -2-2i (but as it is hard coded as + in the comment it is resulting in -2+-2i

Help me understand how to get rid of it?


Solution

  • The problem is that you're explicitly asking to separate the real and imaginary part with a plus sign.

    here's a short version

    class comp(complex):
        def add(self, other):
            print(f'Sum of the two Complex numbers: {self+other}')
        def sub(self, other):
            print(f'Subtraction of the two Complex numbers: {self-other}')
    
    
    x = comp(1, 2)
    y = comp(3, 4)
    x.add(y)
    # Sum of the two Complex numbers: (4+6j)
    x.sub(y)
    # Subtraction of the two Complex numbers: (-2-2j)
            
    

    otherwise

    def sign(x):
       return '+' if x>=0 else ''
    
    class comp:
      
        def __init__(self, real, imag):
            self.real=real
            self.imag=imag
    
        def add(self, other):
            r = self.real + other.real
            i = self.imag + other.imag
            print(f'Sum of the two Complex numbers: {r}{sign(i)}{i}i')
        
        def sub(self, other):
            r = self.real - other.real
            i = self.imag - other.imag
            print(f'Subtraction of the two Complex numbers: {r}{sign(i)}{i}i')
    
    
    x = comp(1, 2)
    y = comp(3, 4)
    x.add(y)
    # Sum of the two Complex numbers: 4+6i
    x.sub(y)
    # Subtraction of the two Complex numbers: -2-2i