Implement a Python class ComplexNumber that represents complex numbers. The class should have methods to perform addition, subtraction, multiplication, and division of complex numbers.
Example 1:
Input: num1 = ComplexNumber(3, 2) num2 = ComplexNumber(1, 7) num1.add(num2) Output: (4+9j)
Example 2:
Input: num1 = ComplexNumber(3, 2) num2 = ComplexNumber(1, 7) num1.subtract(num2) Output: (2-5j)
Remember that the operations on complex numbers follow different rules than operations on regular integers or floats.
class ComplexNumber:
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def add(self, other):
real = self.real + other.real
imaginary = self.imaginary + other.imaginary
return complex(real, imaginary)
def subtract(self, other):
real = self.real - other.real
imaginary = self.imaginary - other.imaginary
return complex(real, imaginary)
def multiply(self, other):
real = self.real * other.real - self.imaginary * other.imaginary
imaginary = self.imaginary * other.real + self.real * other.imaginary
return complex(real, imaginary)
def divide(self, other):
real = (self.real * other.real + self.imaginary * other.imaginary) / (other.real**2 + other.imaginary**2)
imaginary = (self.imaginary * other.real - self.real * other.imaginary) / (other.real**2 + other.imaginary**2)
return complex(real, imaginary)
Unlock AI & Data Science treasures. Log in!