How to use cumulative distribution functions within an interactive simulator

19 Views Asked by At

I am building a simple simulator in python that should simulate an event taking place based on its cumulative distributed function (CDF).

A pseudo-code (in python) for it is shown below for illustration purposes.

import math
import random

x = 0
event_rate = 0.01

for t in range(1000):
  cfd = 1 - math.exp(-x*event_rate)  # Calculates the cumulative distribution at point `t`
  seed = random.random()
  if seed > cfd:
    x += 1   # Increase event counter.
    continue # Event didn't trigger yet.
  else:
    x = 0    # Reset event counter once the event happens.

To me, the code above seems to be correctly calculating the exponential distribution based on the formula below:

$$CFD=1-e^{-t*\lambda}$$

For an event_rate ($\lambda$) of 0.01, I would expect the event to happen once around 100 time steps in average. However, the event happens way more frequently.

I also found out during debugging that the event is being triggered frequently when the probability of the event happening is still too low (is this due to the nature of the random.random() function?). I would expect the event to be triggered more often when the probability of it happening (its CFD) is higher.

I think what I am doing wrong is the seed calculation which I am using to trigger the probabilistic event.

Also, at any time t on the simulation, I believe I am calculating the correct probability of the event happening. But I think I am not "triggering" it correctly in the simulation by just simply comparing the CFD against a random number.

What should I do instead?