Sh3ll
OdayForums


Server : Apache
System : Linux profile 3.10.0-1160.88.1.el7.x86_64 #1 SMP Tue Mar 7 15:41:52 UTC 2023 x86_64
User : apache ( 48)
PHP Version : 8.0.28
Disable Function : NONE
Directory :  /var/www/html/bibhas.ghoshal/IoT_2019/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : //var/www/html/bibhas.ghoshal/IoT_2019/12ComplexNum.py
import math
class ComplexNum(object):
    """A class to implement complex numbers"""
    # real and imaginary parts are stored in real and imag
    def __init__(self, r=0, i=0):
        # complex number, given real and imaginary part
        # defaults to create 0 + i0
        self.real = r  # self equiv to "this" in java
        self.imag = i

    def __str__(self):
        """ Returns a string representation of the complex number"""
        # printed as (x + iy) or (x - iy)
        imag = self.imag
        join = ' +'
        if (imag < 0):
            imag = -imag
            join = ' -'
        self.s = "str"    
        return '(' + str(self.real) + join +' i' + str(imag) + ')'

    def getReal(self):
        """ Returns the real part"""
        return self.real

    def getImag(self):
        """ Returns the imaginary part"""
        return self.imag

    def abs(self):
        """ return the magnitude """
        return math.sqrt(self.real*self.real + self.imag*self.imag)

    def conjugate(self):
        """ return the conjugate """
        return ComplexNum(self.real, -self.imag)

    def __add__(self, oth):
        return ComplexNum(self.real+oth.real, self.imag+oth.imag)

    def __sub__(self, oth):
        return ComplexNum(self.real-oth.real, self.imag-oth.imag)

    def __mul__(self, oth):
        return ComplexNum(self.real*oth.real - self.imag*oth.imag,
                          self.real*oth.imag + self.imag*oth.real)

    
    def __truediv__(self, oth):
        othc = oth.conjugate()
        absSq = oth.abs()
        absSq = absSq * absSq
        
        numr = self * othc
        try:
            return ComplexNum(numr.real/absSq, numr.imag/absSq)
        except:
            raise ValueError("Divison by " + str(oth) + " not defined")
        

   
def test1():
    z1 = ComplexNum()
    z2 = ComplexNum(2, 3)
    z3 = z2.conjugate()
    z4 = z2 * z3
    z5 = ComplexNum(3.5, 0.33)
    print ('z1 = ', z1)
    print ('z2 = ', z2)
    print ('Conjugate of ', z2, ' = ', z3)
    print (z2, ' * ', z3, ' = ', z4)
    print (z2, ' * ', z2, ' = ', z2*z2)
    print (z2, ' + ', z5, ' = ', z2+z5)
    print (z5, ' - ', z2, ' = ', z5-z2)
    print (z5, ' / ', z2, ' = ', z5/z2)
    print (z5, ' / ', z1, ' = ', z5/z1)
    

ZeroDay Forums Mini