2010-09-26 28 views
2

級別:初學者面向對象編程基礎知識(python)

在下面的代碼中,我的'samePoint'函數返回False,我期待True。任何提示?

import math 

class cPoint: 
    def __init__(self,x,y): 
     self.x = x 
     self.y = y 
     self.radius = math.sqrt(self.x*self.x + self.y*self.y) 
     self.angle = math.atan2(self.y,self.x) 
    def cartesian(self): 
     return (self.x, self.y) 
    def polar(self): 
     return (self.radius, self.angle) 

class pPoint: 
    def __init__(self,r,a): 
     self.radius = r 
     self.angle = a 
     self.x = r * math.cos(a) 
     self.y = r * math.sin(a) 
    def cartesian(self): 
     return (self.x, self.y) 
    def polar(self): 
     return (self.radius, self.angle) 

def samePoint(p, q): 
    return (p.cartesian == q.cartesian) 

>>> p = cPoint(1.0000000000000002, 2.0) 
>>> q = pPoint(2.23606797749979, 1.1071487177940904) 
>>> p.cartesian() 
(1.0000000000000002, 2.0) 
>>> q.cartesian() 
(1.0000000000000002, 2.0) 
>>> samePoint(p, q) 
False 
>>> 

來源:麻省理工學院開放式http://ocw.mit.edu計算機科學導論和程序2008年秋季

回答

7

看你的代碼

def samePoint(p, q): 
    return (p.cartesian == q.cartesian) 

p.cartesian,q.cartesian的功能,你是比較函數,而不是函數結果。由於比較兩個不同的功能,結果是假

你應該已經被編碼爲

def samePoint(p, q): 
    return (p.cartesian() == q.cartesian()) 
+0

嗨pyfunc,謝謝你的幫助!它似乎我犯了一個簡單的錯誤,但它會幫助我獲得正確的基礎知識。非常感激! – raoulbia 2010-09-26 13:48:20

4

你是不是呼籲平等的檢查方法。所以你在比較每個方法的方法。

嘗試:

return (p.cartesian() == q.cartesian()) 
+0

感謝CandyMan! – raoulbia 2010-09-26 13:49:45

1

後你得到的函數調用的東西固定的,你就會有浮點的問題。

嘗試,

def is_same_point(p1, p2, e): 
    for c1, c2 in zip(c1, c2): 
     if abs(c1 - c2) > e: 
      return False 
    return True 

我真的很驚訝,它的工作爲你和你發佈的代碼示例。你一定是這樣做的。一般來說,您不能直接比較浮點值是否相等。

更Python的方式來寫上面的函數是

def is_same_point(point1, point2, e): 
    return not any(abs(c1 - c2) > e for c1, c2 in zip(point1, point2)) 

你還是得雖然通過e(對於小量)左右,並且是會得到老的快。

def make_point_tester(e): 
    def is_same_point(point1, point2): 
     return not any(abs(c1 - c2) > e for c1, c2 in zip(point1, point2)) 
    return is_same_point 

is_same_point = make_point_tester(.001) 

你媒體鏈接碰上功能是第一類對象,所以你不應該有這個代碼的麻煩;)

+0

到目前爲止,它一直爲他工作,因爲他沒有通過不同路徑達到相同FP值的情況(即比較5.1到3.0 + 2.1) – 2010-09-26 09:50:06