Bookshelf icon indicating copy to clipboard operation
Bookshelf copied to clipboard

Add a way to generate a random number in any distribution

Open aksiome opened this issue 7 months ago • 0 comments

🗂️ Request Type

Feature

🧩 Feature or Module Name

bs.random

📝 Description

See #286:

To generate a random number in any distribution, I suggest to use a MCMC method such as the well known Metropolis algorithm.

The idea consist in placing a walker randomly in the desired area in wich we want to generate a random number. We then generate randomly a new position for the walker in this area. If the distribution is lower at the new position than at the old one, we accept the move only if a random number between 0 and 1 is lower than the ratio of the distribution at these two positions.

def metropolis(dist, a, b):
    x = np.random.random() * (b - a) + a
    N = 10
    for _ in range(N):
        x2 = np.random.random() * (b - a) + a
        if np.random.random() < dist(x2) / dist(x):
            x = x2
    return x

Image

Originally posted by @VForiel in #286

aksiome avatar May 15 '25 21:05 aksiome