下面是我正在構建的汽車車庫模擬器的代碼。我堅持的是,能夠生成汽車開到某個車庫 (garage1) 直到那個車庫滿了,然后生成的汽車開到第二個車庫。因為我希望我的模擬按時隨機工作。我必須使用某種泊松分布以某種方式生成汽車。但是,如果第一個車庫很忙,我似乎無法獲得有關如何生成它們并讓它們移動到另一個的靈感。(在這里,我只有一個車庫,這是目標) class People(object): def __init__(self,c,xpos,ypos,speed,xgoal,ygoal): self.c=c self.xpos=xpos self.ypos=ypos self.speed=speed self.xgoal=xgoal self.ygoal=ygoal def show(self): #stroke(0) fill(self.c) rectMode(CENTER) rect(self.xpos,self.ypos,20,10) def drive(self): self.xpos=self.xpos + (self.xgoal - self.xpos)*0.05 * self.speed self.ypos=self.ypos + (self.ygoal - self.ypos)*0.05 * self.speed person1=People(color(255,0,0),35,280,1,120,10) person2=People(color(0,255,0),60,280,1,300,15)def setup(): size(450,320)def draw(): person1.show() person1.drive() person2.show() person2.drive()
4 回答

海綿寶寶撒
TA貢獻1809條經(jīng)驗 獲得超8個贊
Numpy 可以從泊松分布中隨機抽取樣本。對于給定的均值和樣本數(shù)量,您可以使用
import numpy as np
mean = 5
N = 100
samples = np.random.poisson(lam=mean, size=N)

慕容森
TA貢獻1853條經(jīng)驗 獲得超18個贊
對您標題中問題的純 Python 答案(這似乎與您的整體問題僅松散相關):
import random, math
def poisson(rate):
t = 0
count = 0
while t < 1:
t -= math.log(random.random())/rate
count += 1
return count - 1
此答案使用的事實是,如果事件以一定速率以指數(shù)分布的到達間隔時間到達,則給定時間單位內的到達次數(shù)以相同的速率遵循泊松分布。雖然它不會像 numpy 解決方案那么快,但它仍然相當快。我能夠在不到一秒的時間內以 rate = 10 生成 100,000 個樣本。
添加回答
舉報
0/150
提交
取消