How to get random numbers with a linear shift of probability?


Warning: count(): Parameter must be an array or an object that implements Countable in /home/styllloz/public_html/qa-theme/donut-theme/qa-donut-layer.php on line 274
0 like 0 dislike
58 views
I need to generate random numbers from A to B, but numbers greater than X must appear in 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 give something like:
0 - 142 1 - 140 2 - 145 3 - 285 4 - 288


The decision "in a forehead" too beat the performance:
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 someone tell me a more elegant algorithm?
PS: JAPANESE is not important
by | 58 views

2 Answers

0 like 0 dislike
Intuition
Imagine that you have a roulette wheel and the ball is equally likely goes for any sector.
For this to implement your task, you need the numbers from A to X to allocate on 1 cell.
And the numbers from X to B, for each, to allocate not 1, and F cells.

Implementation
The length of the "roulette" is produced (X-A) + F * (B-X)
Get a random integer in this range. If it got above X, it remains to divide by F, the difference of the number and X.
by
0 like 0 dislike
from random import randint def shift_rand(a, b, x, f): t = randint(a, (b - x) * f + x) return t if t <= x else (t - x) // f + x
by

Related questions

0 like 0 dislike
2 answers
0 like 0 dislike
2 answers
0 like 0 dislike
2 answers
0 like 0 dislike
7 answers
asked Mar 24, 2019 by AntonioK
110,608 questions
257,187 answers
0 comments
40,473 users