-1

I'm having issues calling the method aleatorio() of my class. I need to create a random point p using the aleatorio() method of my ponto class, so I can then use it in my retangulo class with the interior() method, to basically check if the random point falls in the interior of each of my two rectangles, r1 and r2. However, it seems that I'm not being able to generate the random point p that I need.

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)

As suggested I added the print of d1,d2 which returns: 0 0. d1 and d2 are supposed to be the number of times my random point falls inside r1 and r2, respectively. I guess 0 either means I'm not generating the random point or that I'm simply not counting the number of times it falls inside correctly, but I'm not sure what the reason is.

4

1 回答 1

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

这看起来更好吗?

于 2017-06-02T00:16:45.317 回答