Modeling a Poisson process with 10000 events per minute 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
 A: How are you getting more than $20$ events per second if you are sleeping for $1/20$ of a second between checks? In case you are actually using intervals of length $0.005$ then you could see up to $200$ events, but you are throwing out each event after the first in each interval. This would lead to an average of $200(1-\exp(-167/200)) = 113.225$ per second, with a binomial distribution instead of a Poisson distribution. You might see slightly fewer if you are actually sampling less often than once every $0.005$ seconds. You should at least test how often your loop is run.
A: You only call f only through f(INTERVAL, LAMBDA) which is a constant equal to 0.9997636. This means that you will go through the if block almost every time.
You sleep a constant time roughly equal to $1/20^{th}$ second so will do a bit less than 20 while cycles per second because of the overhead time of function calls. So you should get around 17-19 events per second.
That answers what is going wrong. Now, to fix it, you need to make f and sleep depend on your random variable. I am not ruby-proficient so this is hard for me to tell, but I suggest something like:
def f()
   # Return an exponential waiting time
   - Math.log(random_gen.rand)
end

and
sleep(f()*0.006)

A: If you want to generate events from a Poisson process by generating interarrival times  you choose X such that $F(X)=U$ where $U$ is uniform on $U[0,1]$ and $F(X)=1-\exp(-\lambda X)$.  So you set $U=1-\exp(-\lambda X)$ or $1-U=\exp(-\lambda X)$ or $-\log(1-U)/\lambda =X$.  Generate $10000$ $X's$ this way and then  count how many $X's$ are less than $60$ seconds.  I don't think that is what your code is doing.
