2016-12-14 41 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) 

計算共軛和比分母沒有虛部。