I am trying to model a system that generates events modeled by a Poisson process.
I am using the following ruby code:
INTERVAL = 0.005
LAMBDA = 167.0
events = Hash.new(0)
def f(x, lambda)
1 - Math.exp(-lambda * x)
end
random_gen = Random.new
start = Time.now.to_f
while Time.now.to_i - start < 60
if random_gen.rand < f(INTERVAL, LAMBDA)
bucket = (Time.now.to_f - start).round.to_i
events[bucket] += 1
end
sleep(INTERVAL)
end
I am trying to generate about 10000 events per minute, or 167 events/second, so I am using $\lambda = 167$.
I am using function f as $1 - e^{(-\lambda x)}$ where $x$ is the interval I am sleeping, I am using this function so that the inter-arrival time of events follows an exponential distribution.
However, I am not getting the expected results, this code generates about 7194 events per minute, with a mean of about 117 events per second. I would expect this code to generate 10000 events per minute with an mean of about 167 events per second.
What am I doing wrong?
Thank you for your help.
UPDATE
Fixed typo with sampling time and added random_gen and start definitions
sleep, but if it's similar to that in C-like languages, it's both machine dependent and has very low resolution. You can get a "real-time" simulation completely avoiding the sleep call with virtually no change to your code. – cardinal Jul 1 '12 at 23:30next_time, initialized to zero. Then, ifTime.now.to_f - start < next_time, just continue in the while loop (do nothing). IfTime.now.to_f - start > next_time, then setnext_time = next_time - log(random_gen.rand)/LAMBDAand increment youreventscounter. Nosleepneeded! – cardinal Jul 1 '12 at 23:50login my "code" is the natural logarithm.) – cardinal Jul 1 '12 at 23:52