Skip to content

Conversation

@rht
Copy link
Contributor

@rht rht commented Jul 26, 2022

I'm not sure of the typical values for the input to poisson_rvs.
There are 2 possible followup improvements:

  1. For large mu, you can use the method described in https://stackoverflow.com/questions/69596814/improved-inverse-transform-method-for-poisson-random-variable-generation-in-r
  2. The poisson_rvs could be defined in Cython instead.

Benchmark code:

import time
import random
import math

from scipy.stats import poisson

mean = 7.5

def poisson_rvs(mu):
    p0 = math.exp(-mu)
    F = p0
    i = 0
    sample = random.random()
    while sample >= F:
        i += 1
        F += p0 * (mu ** i) / math.factorial(i)
    return i


scipy_list = []
tic = time.time()
for i in range(1000):
    scipy_list.append(poisson.rvs(mean))
elapsed = time.time() - tic
print("scipy.stats", elapsed, sum(scipy_list) / len(scipy_list))
custom_list = []
tic = time.time()
for i in range(1000):
    custom_list.append(poisson_rvs(mean))
elapsed_custom = time.time() - tic
print("Custom", elapsed_custom, sum(custom_list) / len(custom_list))
print("Speedup", round(elapsed / elapsed_custom, 4))
scipy.stats 0.1656346321105957 7.525
Custom 0.008195161819458008 7.561
Speedup 20.2113

@rht
Copy link
Contributor Author

rht commented Jul 28, 2022

Any update @nunezco2 ? I have one more followup perf PR, but waiting for this one to be merged first.

@snunezcr snunezcr merged commit 5a89831 into ncsa:master Jul 28, 2022
@snunezcr
Copy link
Collaborator

snunezcr commented Jul 28, 2022 via email

@rht
Copy link
Contributor Author

rht commented Jul 28, 2022

The current poisson_rvs is general. It's just that for large mu, there is an even better algorithm.

AngelSaint pushed a commit to AngelSaint/COVID19-mesa that referenced this pull request Nov 8, 2025
perf: Use Python builtin random.random to generate Poisson samples
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants