Informatics2-2020/Lab06
A MathWikiből
(Változatok közti eltérés)
a |
a (→Complex) |
||
(egy szerkesztő 2 közbeeső változata nincs mutatva) | |||
12. sor: | 12. sor: | ||
self.re = real | self.re = real | ||
self.im = imaginary | self.im = imaginary | ||
− | + | ||
def __add__(self, z2): | def __add__(self, z2): | ||
new_re = self.re + z2.re | new_re = self.re + z2.re | ||
26. sor: | 26. sor: | ||
z3 = z1 + z2 | z3 = z1 + z2 | ||
− | print z3 | + | print(z3) |
</python> | </python> | ||
− | * Implement the subtraction, multiplication and division methods (__sub__, __mul__, | + | * Implement the subtraction, multiplication and division methods (__sub__, __mul__, __truediv__). |
* Also implement the <tt>norm</tt> method which returns the length of the complex number. | * Also implement the <tt>norm</tt> method which returns the length of the complex number. | ||
* Improve the __str__ method to handle numbers like this for example: | * Improve the __str__ method to handle numbers like this for example: |
A lap jelenlegi, 2020. március 25., 15:50-kori változata
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