Search code examples
pythonrandomnumpyexponential-distribution

Does Python's random module have a substitute for numpy.random.exponential?


I've been using Numpy's numpy.random.exponential function for a while. I now see that Python's random module has many functions that I didn't know about. Does it have something that replaces numpy.random.exponential? It would be nice to drop the numpy requirement from my project.


Solution

  • If anything about random.expovariate() does not suit your needs, it's also easy to roll your own version:

    def exponential(beta):
        return -beta * math.log(1.0 - random.random())
    

    It seems a bit of an overkill to have a dependency on NumPy just for this functionality.

    Note that this function accepts the mean beta as a parameter, as does the NumPy version, whereas the parameter lambd of random.expovariate() is the inverse of beta.