2017-06-01 74 views
-1

我有問題,調用我的課程的方法aleatorio()。我需要使用我的ponto類的aleatorio()方法創建一個隨機點p,因此我可以在interior()方法的retangulo類中使用它,以基本檢查隨機點是否落入每個矩形的內部, r1r2。但是,似乎我無法生成我需要的隨機點p如何調用該方法?

from random import uniform 
class ponto: 
    def __init__(self,x,y): 
     self.x=float(x) 
     self.y=float(y) 

    def aleatorio(self): 
     ''' Ponto aleatorio com coordenadas 0.0 a 10.0 ''' 
     self.x=uniform(0.0,10.0) 
     self.y=uniform(0.0,10.0) 

class retangulo(): 
    def __init__(self,a,b): 
     self.a=a 
     self.b=b 

    def interior(self,p): 
     ''' Verifica se ponto no interior do retangulo ''' 
     if p.x >= self.a.x and p.x <=self.b.x and p.y >=self.a.y and p.y<=self.b.y: 
      return True 
     return False 

    def area(self): 
     return self.a*self.b 

a1=ponto(0.0,0.0) 
b1=ponto(2.0,2.0) 
r1=retangulo(a1,b1) 
b2=ponto(4.0,4.0) 
r2=retangulo(a1,b2) 

p=ponto(0.4,0.9) 
p.aleatorio() 

d1=0 
d2=0 
for r in range(10000): 
    if r1.interior(p)==True: 
     d1+=1 
    elif r2.interior(p)==True: 
     d2+=1 
print(d1,d2) 

至於建議我加入d1,d2打印返回:0 0d1d2應該是我的隨機點分別落在r1r2之內的次數。我猜0要麼意味着我不會產生隨機點,或者我只是不計算它內部正確的次數,但我不知道是什麼原因。

+0

請提供問題的證據。例如,插入一些打印語句以顯示問題輸出。 – Prune

+0

我從通話中獲取號碼並不困難。究竟是什麼,告訴你沒有隨機點? – Prune

+0

我可以在這段代碼中發現的唯一問題是完全無用的'for範圍(10000):'。 –

回答

0

也許你的麻煩是循環,而不是滾動。 @AlanLeuthard非常正確:該代碼生成一個單一點,然後檢查10000次這兩個矩形的每一箇中是否有相同的點。試着做一個新的起點,通過循環每次:

d1=0 
d2=0 
for r in range(10000): 
    p.aleatorio() 
    if r1.interior(p)==True: 
     d1+=1 
    elif r2.interior(p)==True: 
     d2+=1 

print d1, d2 

輸出:

397 1187 

這是否更好看?

+0

YES IT DOES!剛剛意識到我的錯誤,你是對的,它實際上總是檢查同一點,非常感謝你:) –