ARITHMETIC COMPLEX CLASS
AIM: To implement a class "arithmetic complex" to execute the following functions:
I. To find the conjugation of a complex number.
II. To find the modulus value (|z|).
III. To find the phase value in polar format (radius, θ).
IV. Addition and subtraction of complex numbers.
ALGORITHM:
Define the math library.
Create a class complex_arithmetic and pass parameters (self, re, im).
Define the conjugate function to return the conjugate of the complex number.
Define the modulus function to return the modulus value by using the formula
modulus=(re2+im2)\text{modulus} = \sqrt{(\text{re}^2 + \
text{im}^2)}modulus=(re2+im2).
Define the phase function to return the phase in polar form using the formula
θ=atan2(im, re)\theta = \text{atan2(im, re)}θ=atan2(im, re).
Define functions for addition and subtraction of two complex numbers.
Test the class by creating complex number objects and applying the functions.
PROGRAM :
import math
class Complex:
def __init__(self, real, imag):
self.real = real
self.imag = imag
def conjugate(self):
return complex(self.real, -self.imag)
def polarform(self):
r = (self.real**2 + self.imag**2)**0.5
theta = math.atan2(self.imag , self.real)
return (r, theta)
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 __truediv__(self, other):
conjugate = other.conjugate()
numerator = self * conjugate
denominator = other * conjugate
return Complex(numerator.real / denominator.real, numerator.imag / denominator.real)
def __str__(self):
if self.imag >= 0:
return f"{self.real} + {self.imag}i"
else:
return f"{self.real} - {-self.imag}i"
C1=Complex(3,6)
C2=Complex(2,-5)
print(C1.conjugate())
print(C2.conjugate())
print(C1.polarform())
print(C1+C2)
print(C1-C2)
print(C1*C2)
print(C1/C2)
print(C1)
print(C2)
OUTPUT:
C1.conjugate() = (3-6j)
C2.conjugate() = ( 2 + 5i )
C1.polarform() = (6.708203932499369, 1.1071487177940904)
C1 + C2 = ( 5 + 1i )
C1 - C2 = ( 1 + 11i )
C1 * C2 = ( 36 - 3i )
C1 / C2 = -0.8275862068965517 + 0.9310344827586207i
C1 = ( 3 + 6i )
C2 = ( 2 - 5i )
RESULT:
The arithmetic complex class using python program has been implemented successfully.