Reza Rohani
Reza Rohani

Reputation: 51

How to evaluate beta distribution only once in python?

In a simulation that I am running I have to draw many many values from the same beta distribution. Currently, I am using

import random

...

for i in range(n_Aa):
   h = random.betavariate(a, b) // With some values for 'a' and 'b'

...

This code, however, is very slow. I think it is because the beta distribution is evaluated over and over again, when it could just be evaluated once since it does not change over the course of the simulation. Is there some way of achieving this?

Upvotes: 0

Views: 370

Answers (1)

user2285236
user2285236

Reputation:

You can try numpy's random.beta. It seems to be a lot faster:

import random
import numpy as np
n = 10**6

%timeit [random.betavariate(2, 3) for _ in range(n)]
1 loop, best of 3: 3.83 s per loop

%timeit np.random.beta(2, 3, n)
10 loops, best of 3: 99.7 ms per loop

Upvotes: 3

Related Questions