Sep 2, 2016

Operator overloading in python: Python Arithmetic on Complex numbers

Write a sample program to perform Addition(+), Subtraction(-), Multiplication(*),Division(/) between complex numbers. And also perform Mod(underRoot(Square(real)+square(imaginary))) of complex number. 
from math import pow
class complex:
    def __init__(self, real, imag):
        self.real = real
        self.imag = imag
    def __add__(self, other):
        return complex(self.real+other.real, self.imag+other.imag)
    def __sub__(self, other):
        return complex(self.real-other.real, self.imag-other.imag)
    def __mul__(self, other):
        return complex(self.real*other.real-self.imag*other.imag, self.real*other.imag+self.imag*other.real)
    def __div__(self, other):
            return self.__mul__(complex(other.real, -1*other.imag)).__mul__(complex(1.0/(other.mod().real)**2, 0))
        except Exception as e:
            print e
            return None
    def mod(self):
        return pow(self.real**2+self.imag**2, 0.5)
    def __str__(self, precision=2):
        return str(("%."+"%df"%precision)%float(self.real))+('+' if self.imag>=0 else '-')+str(("%."+"%df"%precision)%float(abs(self.imag)))+'i'

print "Enter real and imaginary part of complex No - 1(separeated by space)" 
A = complex(*map(float, raw_input().strip().split()))
print "Enter real and imaginary part of complex No - 2(separeated by space)" 
B = complex(*map(float, raw_input().strip().split()))

print "Addition: " + str(A+B)
print "Subtraction: " + str(A-B)
print "Multiplication: " + str(A*B)
print "Division: "+ str(A/B)
print "Modulas of complex Number A: " + str(A.mod())
Sample output:-
Enter real and imaginary part of complex No - 1
3 4
Enter real and imaginary part of complex No - 2
2 3
Addition: 5.00+7.00i
Subtraction: 1.00+1.00i
Multiplication: -6.00+17.00i
Division: 1.38-0.08i
Modulas of complex Number A: 5.0

Python provides ability to override inbuilt arithmetic methods like __add__(),__sub__(), etc methods. It is similar to overriding __str__() method to print formatted output(like we have done in above code).For more detail refer this.

What happens internally when we perform + operation between two objects(Remember primitive integer is object in python)?- When we sum two objects in Python, like
a + b
the __add__ method of the a object is called: a.__add__(b)
it means that we can control the result of a sum of two objects by modifying or defining our own __add__ method.

Location: Hyderabad, Telangana, India