Convert a range of integers to another range of integers while keeping an even distribution

127 Views Asked by At

I have a random integer x in the range [A, B] (inclusive).
Is it always possible to convert x to another integer y in the range [C,D] (inclusive) while keeping an even distribution?
This only seems possible if the size of [A,B] and [C,D] are divisible without rest.
Is there any trick I can use to make this possible?

Practical example of what I would like to do:
I get a random integer x in the range [0, 1048576].
I convert x to a new integer y in the range [10, 19].
I repeat the experience a large amount of times.
At the end, I get an even distribution of y=10, y=11, y=12... (≈10% of y=10, ≈10% of y=11, ≈10% of y=12 ...)

Thank you for bearing with me and my questionable math skills.

2

There are 2 best solutions below

5
On

Yes, you're right, if you perform the experiment only once.

If you do an experiment with 1048577 events each with probability $1/1048577$, there's no way you're going to be able to combine those outcomes into larger sets each with probability exactly $1/10$. The best you can get is some approximation.

One possibility would be to repeat the experiment until you get a result that works. For example, if you get a result in the range $[0,1048569]$, take the remainder after division by $10$, and add $10$. Otherwise, repeat the experiment until you get an answer in this range. It is unlikely you'll have to do the experiment many times. In principle there is no guaranteed upper bound to the number of times you'll have to do it, but despite this the average number of experiments you'll need is finite.

4
On

If you want it to be exactly even, you are right that you need the size of $[C,D]$, which is $D-C+1,$ to divide the size of $[A,B]$ evenly. If it doesn't divide evenly but the size of $[A,B]$ is much larger than the size of $[C,D]$, as in your example, it will be very close. Here you start with $1048577$ possibilities and you want to sort them into $10$ bins. You can start by putting $\lfloor \frac {1048577}{10}\rfloor=104857$ in each bin and you have $7$ left over. You can put those each in separate bins. Now some bins have $104858$ and some have $104857$. Although that is not perfectly even, it is only one part in $104857$ off, which is rather small. If that is close enough for you, you are done. If not, you can pull another random number with a range of $10$ to assign each of the left overs to a bin.