Exercise
Advanced Number Systems
Objective
Develop a Python program to represent complex numbers, which consist of a real part and an imaginary part. For a complex number like \( a + bi \) (such as 2 - 3i), \( a \) is the real part and \( b \) is the imaginary part.
1. Create a class called `ComplexNumber` that includes:
- A constructor to initialize the real and imaginary parts.
- Setters and getters for both the real and imaginary parts.
- A method `__str__()` that returns the complex number as a string in the format "(a, b)".
- A method `get_magnitude()` that calculates and returns the magnitude of the complex number using the formula \( \sqrt{a^2 + b^2} \).
- A method `add()` to add two complex numbers together, adding their real and imaginary parts separately.
2. Then, create a test program to verify the functionality of the `ComplexNumber` class by creating instances of the class, testing the methods toString, get_magnitude, and add, and displaying the results.
Example Python Exercise
Show Python Code
import math
class ComplexNumber:
def __init__(self, real, imaginary):
"""
Constructor that initializes the real and imaginary parts of the complex number.
"""
self.real = real
self.imaginary = imaginary
# Setters and getters for the real part
def set_real(self, real):
self.real = real
def get_real(self):
return self.real
# Setters and getters for the imaginary part
def set_imaginary(self, imaginary):
self.imaginary = imaginary
def get_imaginary(self):
return self.imaginary
# __str__() method to represent the complex number as a string
def __str__(self):
return f"({self.real}, {self.imaginary})"
# Method to calculate and return the magnitude of the complex number
def get_magnitude(self):
return math.sqrt(self.real**2 + self.imaginary**2)
# Method to add two complex numbers
def add(self, other):
real_sum = self.real + other.get_real()
imaginary_sum = self.imaginary + other.get_imaginary()
return ComplexNumber(real_sum, imaginary_sum)
# Test program
if __name__ == "__main__":
# Create two complex numbers
c1 = ComplexNumber(2, -3) # Complex number 2 - 3i
c2 = ComplexNumber(1, 4) # Complex number 1 + 4i
# Display the complex numbers as strings
print(f"Complex Number 1: {c1}")
print(f"Complex Number 2: {c2}")
# Display the magnitude of the complex numbers
print(f"Magnitude of Complex Number 1: {c1.get_magnitude()}")
print(f"Magnitude of Complex Number 2: {c2.get_magnitude()}")
# Add the two complex numbers
sum_result = c1.add(c2)
print(f"Sum of Complex Number 1 and 2: {sum_result}")
Output
Complex Number 1: (2, -3)
Complex Number 2: (1, 4)
Magnitude of Complex Number 1: 3.605551275463989
Magnitude of Complex Number 2: 4.123105625617661
Sum of Complex Number 1 and 2: (3, 1)
Share this Python Exercise