A
A
Alexey Babiev2019-01-30 19:56:01
Algorithms
Alexey Babiev, 2019-01-30 19:56:01

How to get random numbers with linear probability shift?

I need to generate random numbers from A to B, but numbers larger than X should appear F times more often. X lies between A and B
That is, the script

def shift_rand(a, b, x, f):
    #???

rnd = [shift_rand(0, 4, 2, 2) for i in range(1000)]

for i in range(5):
    print(i, '-', rnd.count(i))

should output something like:
0 - 142
1 - 140
2 - 145
3 - 285
4 - 288

The head-on solution hits performance too hard:
def shift_rand(a, b, x, f):
    m = []
    for i in range(a, b + 1):
        if i <= x:
            m.append(i)
        else:
            for j in range(f):
                m.append(i)
    return m[random.randint(0, len(m) - 1)]

Can anyone suggest a more elegant algorithm?
PS: PL is not important

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2019-01-30
@axsmak

Intuition
Imagine that you have a roulette wheel, and the ball hits any sector with equal probability.
In order to implement your task on this, you need to select 1 cell for numbers from Аto . And for numbers from to , for each, select not 1, but cells. Implementation The length of the "roulette" is obtained Get a random integer on this range. If it hits above X, it remains to divide by F the difference between the number rolled and X. X

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question