如何在Python中实现支持复数运算(加减乘除、幂、范数)的Complex类
实现支持完整运算的Python Complex类
嘿,我来帮你搞定这个自定义Complex类的需求!要实现支持所有复数运算的类,我们需要重载Python的特殊方法(比如__add__、__mul__这些),再加上自定义的范数、幂运算等方法。下面是一个完整的可运行实现,我会把关键部分给你拆解清楚:
完整代码实现
import math class Complex: def __init__(self, real=0, imag=0): self.real = float(real) self.imag = float(imag) # 字符串表示,方便打印和调试 def __str__(self): if self.imag >= 0: return f"{self.real}+{self.imag}i" else: return f"{self.real}{self.imag}i" def __repr__(self): return f"Complex({self.real}, {self.imag})" # 加法运算 def __add__(self, other): if isinstance(other, Complex): return Complex(self.real + other.real, self.imag + other.imag) # 支持和实数相加 elif isinstance(other, (int, float)): return Complex(self.real + other, self.imag) else: raise TypeError("Unsupported operand type for +") # 反向加法(比如实数+复数) def __radd__(self, other): return self.__add__(other) # 减法运算 def __sub__(self, other): if isinstance(other, Complex): return Complex(self.real - other.real, self.imag - other.imag) elif isinstance(other, (int, float)): return Complex(self.real - other, self.imag) else: raise TypeError("Unsupported operand type for -") # 反向减法 def __rsub__(self, other): if isinstance(other, (int, float)): return Complex(other - self.real, -self.imag) else: raise TypeError("Unsupported operand type for -") # 乘法运算 def __mul__(self, other): if isinstance(other, Complex): # (a+bi)(c+di) = (ac-bd) + (ad+bc)i real_part = self.real * other.real - self.imag * other.imag imag_part = self.real * other.imag + self.imag * other.real return Complex(real_part, imag_part) elif isinstance(other, (int, float)): return Complex(self.real * other, self.imag * other) else: raise TypeError("Unsupported operand type for *") # 反向乘法 def __rmul__(self, other): return self.__mul__(other) # 除法运算 def __truediv__(self, other): if isinstance(other, Complex): # 分母有理化:(a+bi)/(c+di) = [(a+bi)(c-di)]/(c²+d²) denominator = other.real ** 2 + other.imag ** 2 if denominator == 0: raise ZeroDivisionError("Division by zero complex number") real_part = (self.real * other.real + self.imag * other.imag) / denominator imag_part = (self.imag * other.real - self.real * other.imag) / denominator return Complex(real_part, imag_part) elif isinstance(other, (int, float)): if other == 0: raise ZeroDivisionError("Division by zero") return Complex(self.real / other, self.imag / other) else: raise TypeError("Unsupported operand type for /") # 反向除法 def __rtruediv__(self, other): if isinstance(other, (int, float)): return Complex(other, 0).__truediv__(self) else: raise TypeError("Unsupported operand type for /") # 幂运算(支持整数和实数指数) def __pow__(self, power): if not isinstance(power, (int, float)): raise TypeError("Power must be an integer or float") # 转换为极坐标:r = |z|, theta = arg(z) r = math.hypot(self.real, self.imag) theta = math.atan2(self.imag, self.real) # z^n = r^n * (cos(nθ) + i sin(nθ)) new_r = r ** power new_theta = theta * power real_part = new_r * math.cos(new_theta) imag_part = new_r * math.sin(new_theta) # 处理浮点精度问题,接近0的数直接设为0 real_part = round(real_part, 10) if abs(real_part) < 1e-10 else real_part imag_part = round(imag_part, 10) if abs(imag_part) < 1e-10 else imag_part return Complex(real_part, imag_part) # 范数/模长(绝对值) def __abs__(self): return math.hypot(self.real, self.imag) # 可选:共轭复数方法 def conjugate(self): return Complex(self.real, -self.imag)
关键功能说明
咱们来逐个看看核心部分的实现思路:
1. 初始化与字符串表示
__init__:把实部和虚部转成浮点数,避免整数运算的精度问题__str__:返回友好的人类可读格式,比如3+4i或者2-5i__repr__:返回类的构造器形式,方便调试时查看实例细节
2. 基本算术运算
我重载了__add__、__sub__、__mul__、__truediv__这些特殊方法,同时实现了对应的反向方法(比如__radd__),这样不仅支持复数+实数,也能支持实数+复数的场景,符合Python的运算习惯。
3. 幂运算
复数的幂运算用极坐标转换会更简单:先把复数转成r(cosθ + i sinθ)的形式,然后根据棣莫弗公式,z^n = r^n (cos(nθ) + i sin(nθ)),最后再转回笛卡尔坐标。另外我还处理了浮点精度问题,把极小的数近似为0,避免出现类似1e-16i这种奇怪的输出。
4. 范数/模长
通过__abs__方法实现,直接返回复数的模长,也就是sqrt(real² + imag²),用math.hypot计算更高效且避免溢出。
5. 额外功能:共轭复数
加了一个conjugate方法,返回当前复数的共轭(虚部取反),这也是复数常用的操作之一。
使用示例
你可以这样测试这个类:
# 创建复数实例 z1 = Complex(3, 4) z2 = Complex(1, -2) # 基本运算 print(z1 + z2) # 输出: 4.0+2.0i print(z1 * z2) # 输出: 11.0-2.0i print(z1 / z2) # 输出: -1.0+2.0i # 和实数运算 print(z1 + 5) # 输出: 8.0+4.0i print(10 - z1) # 输出: 7.0-4.0i # 幂运算 print(z1 ** 2) # 输出: -7.0+24.0i print(z1 ** 0.5)# 输出: 2.0+1.0i(也就是3+4i的平方根) # 范数和共轭 print(abs(z1)) # 输出: 5.0 print(z1.conjugate()) # 输出: 3.0-4.0i
这个实现已经覆盖了你提到的所有需求,而且兼容Python的常规运算逻辑,你可以直接用或者根据自己的需求再调整细节~
内容的提问来源于stack exchange,提问作者Rambo




