2016-12-14 31 views
2

已经实施了一个名为ComplexNumbers类,这是代表复数,我不允许使用内置的的类型了点。 我已经覆盖了运营商(__add____sub____mul____abs____str_允许进行基本操作 但现在我只能和覆盖__div__操作的Python司复数,而无需使用内建类型和运算符

允许使用:。

我“M使用float表示该数字的虚部和float代表相对部分

我已经尝试过:

  • 我抬头看如何执行复杂的数字的分工(手写)
  • 我曾经做过一个计算实例
  • 思考如何以编程方式实现它没有任何好的结果

说明如何将复杂的数字:

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) 
+0

你不允许使用int吗? –

+0

@PatrickHaugh我会更新实际部分的问题类型是'float'虚部的类型是'int' –

+0

好吧,这就是您需要的所有东西。在划分算法中你遇到麻烦了吗? –

回答

3

我认为这应该足够了:

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__ 
0

由于@PatrickHaugh的提示,我能够解决的问题。这是我的解决方案:

def __div__(self, other): 
     conjugation = ComplexNumber(other.re, -other.im) 
     denominatorRes = other * conjugation 
     # denominator has only real part 
     denominator = denominatorRes.re 
     nominator = self * conjugation 
     return ComplexNumber(nominator.re/denominator, nominator.im/denominator) 

计算共轭和比分母没有虚部。

相关问题