Python sdut—oop—1简单的复数运算
时间: 2024-10-23 09:19:43 浏览: 82
在Python中,使用OOP(Object-Oriented Programming,面向对象编程)设计复杂的数据结构,如复数,是一种常见的实践。复数是一个由实部和虚部分组成的数,通常表示为`a + bj`的形式,其中`a`是实数,`b`是虚数,`j`代表虚数单位。
创建一个简单的复数类,我们可以这样实现:
```python
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 subtract(self, other):
return ComplexNumber(self.real - other.real, self.imag - other.imag)
# 乘法方法
def multiply(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 sqrt(self):
magnitude = (self.real ** 2 + self.imag ** 2) ** 0.5
angle = math.atan2(self.imag, self.real)
return ComplexNumber(magnitude ** 0.5 * math.cos(angle), magnitude ** 0.5 * math.sin(angle))
# 使用示例
z1 = ComplexNumber(3, 4)
z2 = ComplexNumber(-1, 2)
print(f"z1 = {z1}, z2 = {z2}")
sum_complex = z1.add(z2)
diff_complex = z1.subtract(z2)
product_complex = z1.multiply(z2)
sqrt_complex = z1.sqrt()
```
在这个例子中,我们定义了一个`ComplexNumber`类,它有四个方法(加法、减法、乘法和平方根),可以对复数进行基本运算。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)