编写python程序,实现一个复数类,要求是支持复数的加减乘除和指数运算,支持求模,求相角,支持复数的打印输出。对设计的复数类进行测试。(测试用例自己定)。
时间: 2024-09-24 13:03:40 浏览: 42
测量程序编制 - python 08数据类型:Number(数字)-概述.pptx
为了编写一个复数类,我们可以定义一个名为`ComplexNumber`的类,包含实部和虚部属性,以及相应的运算方法。下面是简单的实现:
```python
import math
class ComplexNumber:
def __init__(self, real=0, imag=0):
self.real = real
self.imag = imag
# 加法
def __add__(self, other):
return ComplexNumber(self.real + other.real, self.imag + other.imag)
# 减法
def __sub__(self, other):
return ComplexNumber(self.real - other.real, self.imag - other.imag)
# 乘法
def __mul__(self, other):
real_part = self.real * other.real - self.imag * other.imag
imag_part = self.real * other.imag + self.imag * other.real
return ComplexNumber(real_part, imag_part)
# 除法
def __truediv__(self, other):
denominator = other.real**2 + other.imag**2
if denominator == 0:
raise ZeroDivisionError("Cannot divide by zero")
real_part = (self.real * other.real + self.imag * other.imag) / denominator
imag_part = (self.imag * other.real - self.real * other.imag) / denominator
return ComplexNumber(real_part, imag_part)
# 指数运算
def __pow__(self, power):
if isinstance(power, complex):
return pow(self, power.real) * pow(complex(1, power.imag), power.imag)
else:
return math.exp(power * math.log(self))
# 求模
def modulus(self):
return (self.real**2 + self.imag**2)**0.5
# 求相角
@staticmethod
def phase(angle):
angle_rad = math.radians(angle)
return ComplexNumber(math.cos(angle_rad), math.sin(angle_rad))
# 打印输出
def __str__(self):
return f"{self.real} + {self.imag}i"
# 测试用例
test_cases = [
(ComplexNumber(1, 2), ComplexNumber(3, 4), ComplexNumber(4, 6)),
(ComplexNumber(2, 0), ComplexNumber(-2, 0), ComplexNumber(0, 0)),
(ComplexNumber(1, 1), ComplexNumber(1, 1), ComplexNumber(0, 0)),
]
for case in test_cases:
result = case[0] + case[1]
print(f"Addition: {case[0]} + {case[1]} = {result}")
result = case[0] - case[1]
print(f"Subtraction: {case[0]} - {case[1]} = {result}")
result = case[0] * case[1]
print(f"Multiplication: {case[0]} * {case[1]} = {result}")
try:
result = case[0] / case[1]
print(f"Division: {case[0]} / {case[1]} = {result}")
except ZeroDivisionError as e:
print(e)
result = case[0]**2
print(f"Square: {case[0]}^2 = {result}")
c = ComplexNumber.phase(math.pi / 2)
print(f"Phase of sqrt(-1): {c}")
result = abs(case[0])
print(f"Modulus of {case[0]}: {result}")
```
这个示例展示了复数的基本操作,包括加减乘除和指数运算,以及模和相角的计算。在测试部分,我们使用了一些预定义的测试案例来验证类的行为。
阅读全文