Informatics2-2020/Lab06

A MathWikiből

previous up next

Exercises

Complex

You have to add methods to the Complex class from the lecture:

class Complex(object):
    def __init__(self, real, imaginary):
        self.re = real
        self.im = imaginary
 
    def __add__(self, z2):
        new_re = self.re + z2.re
        new_im = self.im + z2.im
        return Complex(new_re, new_im)
 
    # used by print
    def __str__(self):
        return str(self.re) + " + " + str(self.im) + "i"
 
z1 = Complex(4, 3)
z2 = Complex(-2, 1)
z3 = z1 + z2
 
print(z3)
  • Implement the subtraction, multiplication and division methods (__sub__, __mul__, __truediv__).
  • Also implement the norm method which returns the length of the complex number.
  • Improve the __str__ method to handle numbers like this for example:
2 - 4i
5i
2

For testing use this (or you can use other tests):

k1 = Complex(4, 3)
k2 = Complex(-2, 1)
k3 = Complex(4, 1)
 
print k1 + k2
print k1 - k3
print k2 * k1
print k3 / k1
print k1.norm()

hazi@math.bme.hu

reservation_1
reservation_2
reservation_3
reservation_4
reservation_5
whowins

previous up next

Személyes eszközök