车库模拟器 - 生成随机泊松分布
Car garage simulator- Generate random poisson distribution
下面是我正在构建的车库模拟器的代码。我坚持的是,能够生成汽车开到某个车库(车库 1)直到那个车库满了,然后生成的汽车开到第二个车库。
因为我希望我的模拟按时随机工作。我必须使用某种泊松分布以某种方式生成汽车。但是,如果第一个车库很忙,我似乎无法获得关于如何生成它们并让它们移动到另一个的任何灵感。
(在此,我只有一个车库,这是目标)
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()
Numpy 可以从泊松分布中抽取随机样本。对于给定的平均值和样本数量,您可以使用
import numpy as np
mean = 5
N = 100
samples = np.random.poisson(lam=mean, size=N)
对您标题中问题的纯粹 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
这个答案使用了这样一个事实,即如果事件以 exponentially-distributed 到达间隔时间以特定速率到达,则给定时间单位内到达的数量以相同的速率服从泊松分布。虽然它不像 numpy 解决方案那么快,但它仍然相当快。我能够在不到一秒的时间内以 rate = 10 生成 100,000 个样本。
下面是我正在构建的车库模拟器的代码。我坚持的是,能够生成汽车开到某个车库(车库 1)直到那个车库满了,然后生成的汽车开到第二个车库。
因为我希望我的模拟按时随机工作。我必须使用某种泊松分布以某种方式生成汽车。但是,如果第一个车库很忙,我似乎无法获得关于如何生成它们并让它们移动到另一个的任何灵感。 (在此,我只有一个车库,这是目标)
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()
Numpy 可以从泊松分布中抽取随机样本。对于给定的平均值和样本数量,您可以使用
import numpy as np
mean = 5
N = 100
samples = np.random.poisson(lam=mean, size=N)
对您标题中问题的纯粹 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
这个答案使用了这样一个事实,即如果事件以 exponentially-distributed 到达间隔时间以特定速率到达,则给定时间单位内到达的数量以相同的速率服从泊松分布。虽然它不像 numpy 解决方案那么快,但它仍然相当快。我能够在不到一秒的时间内以 rate = 10 生成 100,000 个样本。