Question

Python has the complex class for performing complex number arithmetic. For this assignment, you will design...

Python has the complex class for performing complex number arithmetic. For this assignment, you will design and implement your own Complex class. Note that the complex class in Python is named in lowercase, while our custom Complex class is named with C in uppercase.

A complex number is of the form a + bi, where a and b are real numbers and i is √-1. The numbers a and b are known as the real part and the imaginary part of the complex number, respectively.

You can perform addition, subtraction, multiplication, and division for complex numbers using the following formulas:

(a + bi) + (c + di) = (a + c) + (b + d)i

(a + bi) - (c + di) = (a - c) + (b - d)i

(a + bi) * (c + di) = (ac - bd) + (bc + ad)i

(a + bi) / (c + di) = (ac + bd)/(c2 + d2) + (bc - ad)i/(c2 + d2)

You can also obtain the absolute value (or length) of a complex number using the formula:

|a + bi| = _______ √ a2 + b2

Implement a class named Complex for representing complex numbers with methods _ _add_ _, _ _sub_ _, _ _mul_ _, _ _truediv_ _, and _ _abs_ _ for performing complex-number operations using +, -, *, /, and abs(). Note: In python 3, _ _truediv_ _ is used to override / and _ _floordiv_ _ is used to override //. The _ _abs_ _(self) special method is used to override the absolute value function; this will allow you to write abs(c), where c is an object of the class Complex. Also, implement the comparison methods _ _eq_ _, _ _ne_ _, _ _lt_ _, ...etc. to compare two Complex numbers based on their length. For the purpose of this assignment, assume that Complex numbers are compared based on the values of their lengths. So, for two Complex numbers c1 and c2, c1 is less than c2, if and only if abs(c1) < abs(c2). Similarly c1 equals c2 if and only if abs(c1) equals abs(c2). The methods _ _eq_ _ and _ _ne_ _ should allow you to compare a Complex number with objects of other types for equality and inequality, respectively.

This is the constructor __init__(self, a = 0, b = 0) to create a complex number a + bi with the default values 0 and 0 for a and b. Your _ _str_ _ method returns the Complex number as a string of the form (a, bi) (it should look as in the sample output below.) If b is 0, it simply returns a --without parentheses. Likewise if a is 0, it returns bi. If both a and b are 0, it returns the string 0. So, the parentheses will be part of the string representation only when both a and b are not 0.

The main function is provided and the code should go with it--copy and paste after the code of the class--

def main():

def main():
    input_line = input("Enter the first complex number: ")
    input_line = list(map(float,input_line.split()))
    a, b = input_line[0], input_line[1]
    c1 = Complex(a, b)
    input_line = input("Enter the second complex number: ")
    input_line = list(map(float,input_line.split()))
    a, b = input_line[0], input_line[1]
    c2 = Complex(a, b)
   
    print()
    print("c1 is", c1)
    print("c2 is", c2)
    print("|" + str(c1) + "| = " + str(abs(c1)))
    print("|" + str(c2) + "| = " + str(abs(c2)))
    
    print(c1, " + ", c2, " = ", c1 + c2)
    print(c1, " - ", c2, " = ", c1 - c2)
    print(c1, " * ", c2, " = ", c1 * c2)
    print(c1, " / ", c2, " = ", c1 / c2)
    
    print("Is c1 < c2?", c1 < c2)
    print("Is c1 <= c2?", c1 <= c2)
    print("Is c1 > c2?", c1 > c2)
    print("Is c1 >= c2?", c1 >= c2)
    print("Is c1 == c2?", c1 == c2)
    print("Is c1 != c2?", c1 != c2)
    print("Is c1 == 'Hello There'?", c1 == 'Hello There')
    print("Is c1 != 'Hello There'?", c1 != 'Hello There')
    
main()

Here is a example of what the output should look like

>>> main()
Enter the first complex number: 2.5 4.5
Enter the second complex number: -2.5 11.2

c1 is (2.5, 4.5i)
c2 is (-2.5, 11.2i)
|(2.5, 4.5i)| = 5.1478150704935
|(-2.5, 11.2i)| = 11.475626344561764
(2.5, 4.5i) + (-2.5, 11.2i) = 15.7i
(2.5, 4.5i) - (-2.5, 11.2i) = (5.0, -6.699999999999999i)
(2.5, 4.5i) * (-2.5, 11.2i) = (-56.65, 16.75i)
(2.5, 4.5i) / (-2.5, 11.2i) = (0.335257043055661, -0.2980484471106386i)
Is c1 < c2? True
Is c1 <= c2? True
Is c1 > c2? False
Is c1 >= c2? False
Is c1 == c2? False
Is c1 != c2? True
Is c1 == 'Hello There'? False
Is c1 != 'Hello There'? True
>>> main()

Here is what in have so far (just the class function but the main() function that is given should be there)

class Complex(object):
def __init__(self, a=0, b=0):
'''create a complex number a +bi with default values 0 and 0 for a and b'''
self._a = a
self._b = b

def __str__(self):

def __add__(self, other):
'''add method returns the sum of two complex numbers'''
  return (self._a + other._a) + (self._b + other._b)

def __sub__(self, other):
'''sub method subtracts two complex numbers'''

def __mul__(self, other):
'''mul method multiplies two compex numbers'''

def __truediv__(self, other):
'''truediv method devides two complex numbers'''
  
def __abs__(self):
'''abs method returns absolute value for two comlex numbers'''

def __eq__(self, other):

def __ne__(self, other):

def __lt__(self, other):

def __le__(self, other):

def __gt__(self, other):

def __ge__(self, other):
  

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Screenshot:

CODE:

import math

class Complex(object):
    def __init__(self, a=0, b=0):
        '''create a complex number a +bi with default values 0 and 0 for a and b'''
        self._a = a
        self._b = b
      
    def __str__(self):
        if (self._a != 0) and (self._b != 0):
            return '('+str(self._a)+','+str(self._b)+ 'i)'
        elif self._a != 0:
            return str(self._a)
        elif self._b != 0:
            return str(self._b) + 'i'
      
    def __add__(self, other):
        '''add method returns the sum of two complex numbers'''
        return Complex(self._a + other._a,
                           self._b + other._b)
      
    def __sub__(self, other):
        '''sub method subtracts two complex numbers'''
        return Complex(self._a - other._a,
                           self._b - other._b)
      
    def __mul__(self, other):
        '''mul method multiplies two compex numbers'''
        return Complex(self._a*other._a - self._b*other._b,
                           self._b*other._a + self._a*other._b)
      
    def __truediv__(self, other):
        '''truediv method devides two complex numbers'''
        sr, si, ore, oi = self._a, self._b, other._a, other._b # short forms
        r = float(ore**2 + oi**2)
        return Complex((sr*ore+si*oi)/r, (si*ore-sr*oi)/r)
        
    def __abs__(self):
        '''abs method returns absolute value for two comlex numbers'''
        return math.sqrt(self._a**2 + self._b**2)
      
    def __eq__(self, other):
        if not isinstance(other, Complex):
            return NotImplemented
        return abs(self)==abs(other)
      
    def __ne__(self, other):
        if not isinstance(other, Complex):
            return NotImplemented
        return abs(self)!=abs(other)
      
    def __lt__(self, other):
        return abs(self)<abs(other)
      
    def __le__(self, other):
        return abs(self)<=abs(other)
      
    def __gt__(self, other):
        return abs(self)>abs(other)
      
    def __ge__(self, other):
        return abs(self)>=abs(other)
  
def main():
    input_line = input("Enter the first complex number: ")
    input_line = list(map(float,input_line.split()))
    a, b = input_line[0], input_line[1]
    c1 = Complex(a, b)
    input_line = input("Enter the second complex number: ")
    input_line = list(map(float,input_line.split()))
    a, b = input_line[0], input_line[1]
    c2 = Complex(a, b)
    print()
    print("c1 is", c1)
    print("c2 is", c2)
    print("|" + str(c1) + "| = " + str(abs(c1)))
    print("|" + str(c2) + "| = " + str(abs(c2)))
    print(c1, " + ", c2, " = ", c1 + c2)
    print(c1, " - ", c2, " = ", c1 - c2)
    print(c1, " * ", c2, " = ", c1 * c2)
    print(c1, " / ", c2, " = ", c1 / c2)
    print("Is c1 < c2?", c1 < c2)
    print("Is c1 <= c2?", c1 <= c2)
    print("Is c1 > c2?", c1 > c2)
    print("Is c1 >= c2?", c1 >= c2)
    print("Is c1 == c2?", c1 == c2)
    print("Is c1 != c2?", c1 != c2)
    print("Is c1 == 'Hello There'?", c1 == 'Hello There')
    print("Is c1 != 'Hello There'?", c1 != 'Hello There')

Add a comment
Know the answer?
Add Answer to:
Python has the complex class for performing complex number arithmetic. For this assignment, you will design...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • A complex number is a number of the form a + bi, where a and b...

    A complex number is a number of the form a + bi, where a and b are real numbers √ and i is −1. The numbers a and b are known as the real and the imaginary parts, respectively, of the complex number. The operations addition, subtraction, multiplication, and division for complex num- bers are defined as follows: (a+bi)+(c+di) = (a+c)+(b+d)i (a+bi)−(c+di) = (a−c)+(b−d)i (a + bi) ∗ (c + di) = (ac − bd) + (bc + ad)i (a...

  • A complex number is a number in the form a + bi, where a and b...

    A complex number is a number in the form a + bi, where a and b are real numbers and i is sqrt( -1). The numbers a and b are known as the real part and imaginary part of the complex number, respectively. You can perform addition, subtraction, multiplication, and division for complex numbers using the following formulas: a + bi + c + di = (a + c) + (b + d)i a + bi - (c + di)...

  • JAVA PROGRAMMING A complex number is a number in the form a + bi, where a...

    JAVA PROGRAMMING A complex number is a number in the form a + bi, where a and b are real numbers and i is V-1. The numbers a and b are known as the real part and imaginary part of the complex number, respectively. You can perform addition, subtraction, multiplication, and division for complex numbers using the following formulas: a + bi + c + di = (a + c) + (b + di a + bi - (c +...

  • c++ 2) Complex Class A complex number is of the form a+ bi where a and...

    c++ 2) Complex Class A complex number is of the form a+ bi where a and b are real numbers and i 21. For example, 2.4+ 5.2i and 5.73 - 6.9i are complex numbers. Here, a is called the real part of the complex number and bi the imaginary part. In this part you will create a class named Complex to represent complex numbers. (Some languages, including C++, have a complex number library; in this problem, however, you write the...

  • 11p Python Language Read the following code for oofraction. import oofraction class OOFraction: def main(): fl...

    11p Python Language Read the following code for oofraction. import oofraction class OOFraction: def main(): fl = oofraction.o0Fraction( 2, 5) f2 = oofraction.o0Fraction ( 1, 3) f3 = f1 + f2 print (str(3)) main() def __init__(self, Num, Den): self.mNum = Num self.mDen = Den return def_add_(self,other): num = self.mNumother.mDen + other.mNum*self.mDen den = self.mDen*other.mDen f = OOFraction(num,den) return f 1. Write the output below. def_str_(self): s = str( self.mNum )+"/" + str( self.mDen) returns 2. Write a class called wholeNum...

  • Python only please, thanks in advance. Type up the GeometricObject class (code given on the back...

    Python only please, thanks in advance. Type up the GeometricObject class (code given on the back of the paper). Name this file GeometricObjectClass and store it in the folder you made (xxlab14) 1. Design a class named Rectangle as a subclass of the GeometricObject class. Name the file RectangleClass and place it in the folder. 2. The Rectangle class contains Two float data fields named length and width A constructor that creates a rectangle with the specified fields with default...

  • Create a class called Complex for performing arithmetic with complex numbers. Complex numbers have the form:...

    Create a class called Complex for performing arithmetic with complex numbers. Complex numbers have the form: realPart + imaginaryPart * i where i is √-1 Use double variables to represent the private data of the class. Provide a constructor that enables an object of this class to be initialized when it’s declared. The constructor should contain default values of (1,1) i.e. 1 for the real part and 1 for the imaginary part. Provide public member functions that perform the following...

  • Hello, In Python Enhance the prior assignment by doing the following 1) Create a class that...

    Hello, In Python Enhance the prior assignment by doing the following 1) Create a class that contain all prior functions MyLib # This function adds two numbers def addition(a, b): return a + b # This function subtracts two numbers def subtraction(a, b): return a - b # This function multiplies two numbers def multiplication(a, b): return a * b # This function divides two numbers # The ZeroDivisionError exception is raised when division or modulo by zero takes place...

  • Please code in Python Revise the AbstractBag class so that it behaves as a subclass of...

    Please code in Python Revise the AbstractBag class so that it behaves as a subclass of AbstractCollection provided in the file abstractcollection.py. Abstractcollection.py code: class AbstractCollection(object):     """An abstract collection implementation."""     # Constructor     def __init__(self, sourceCollection = None):         """Sets the initial state of self, which includes the         contents of sourceCollection, if it's present."""         self.size = 0         if sourceCollection:             for item in sourceCollection:                 self.add(item)     # Accessor methods     def isEmpty(self):         """Returns True if len(self) == 0, or False otherwise."""         return len(self) == 0...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT