不使用内置类型和运算符的复数Python划分 [英] Python Division Of Complex Numbers Without Using Built In Types and Operators
问题描述
我必须实现一个名为ComplexNumbers
的类,该类表示一个复数,并且不允许为此使用内置类型.
我已经覆盖了允许执行基本操作的运算符(__add__
,__sub__
,__mul__
,__abs__
,__str_
).
但是现在我不得不覆盖__div__
运算符.
I have to implement a class called ComplexNumbers
which is representing a complex number and I'm not allowed to use the built in types for that.
I already have overwritten the operators (__add__
, __sub__
, __mul__
, __abs__
, __str_
which allows to perform basic operations.
But now I'm stuck with overwriting the __div__
operator.
允许使用:
我用float
表示数字的虚部,用float
表示相关部分.
I'm using float
to represent the imaginary part of the number and float
to represent the rel part.
我已经尝试过的:
- 我查看了如何对复数进行除法(手写)
- 我已经完成了示例计算
- 考虑如何以编程方式实现它而没有任何良好结果
关于如何对复数进行除法的说明:
Explanation of how to divide complex numbers:
http://www .mathwarehouse.com/algebra/complex-number/divide/how-to-divide-complex-numbers.php
我的乘法实现:
def __mul__(self, other):
real = (self.re * other.re - self.im * other.im)
imag = (self.re * other.im + other.re * self.im)
return ComplexNumber(real, imag)
推荐答案
我认为这足够了:
def conjugate(self):
# return a - ib
def __truediv__(self, other):
other_into_conjugate = other * other.conjugate()
new_numerator = self * other.conjugate()
# other_into_conjugate will be a real number
# say, x. If a and b are the new real and imaginary
# parts of the new_numerator, return (a/x) + i(b/x)
__floordiv__ = __truediv__
这篇关于不使用内置类型和运算符的复数Python划分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!