# Converting scales of True Random Numbers causes distribution de-uniformization

Hi,

i'm using one data file from random.org to get true random numbers.
Each file is a stream of random bits and as such we're always confined
to [0, 2^N -1] interval of values.... for simplicity I read a byte at a
time so it's [0, 255] interval.

For curiosity I made an histogram of the 1MB file of random data, the
result is a uniform distribution with
numbers from 0 to 255.
But if I try to generate numbers in a 0 to 49 scale the histogram
doesn't get uniform...

Results from a 0..255 histogram:
[3963, 3846, 3843, 3964, 3910, 3894, 3909, 3851, 3957, 3872, 3943,
3866, 3905, 3818, 3890, 3924, 3946, 3882, 3887, 3896, 3884, 3877,
3869, 3880, 3829, 3947, ................................. 3875,
3863, 3969, 3898, 3869, 3854, 3962, 3957, 3909, 3986, 3873, 3918,
3944, 3964, 3871, 3829, 3803, 3952, 3964, 3969, 4007, 3941]

Results from a 0..49 histogram:
[11566, 19543, 23316, 19557, 19399, 19460, 19596, 23472, 19415, 19328,
19246, 19858, 23500, 19602, 19965, 19226, 19628, 23415, 19679, 19840,
19415, 19585, 23376, 19657, 19487, 19511, 19569, 23481, 19459, 19449,
19467, 19477, 23591, 19444, 19433, 19522, 19636, 23505, 19726, 19776,
19488, 19381, 23341, 19557, 19222, 19370, 19582, 23546, 19468, 11868]

Notice the significant smaller first and last indexes, as well as the
pattern: 19K 19K 19K 19K 23K

My code:
/*
* returns an int value between [1, upperLimit]
*/
public int nextInt(int upperLimit) {
float ratio, res;

ratio = (float)255.0 / (float)(upperLimit-1);
res = (float)readNextByte() / ratio;
return Math.round(res)+1;
}

What am I missing here? Is there any way to fix this???

Thank you very much for your help.

.

• Follow-Ups: