Python: rounding error distorts uniform distribution

I need to try 10 evenly distributed random numbers between 0 and 1. So I thought the following code in python would do this:

positions = []
for dummy_i in range(1000000):
    positions.append(round(random.random(),1))

However, when transferring the result to the histogram, the result is as follows:

Frequency of numbers rounded to 1 decimal point

Thus, rounding seems to destroy the uniform distribution generated by random.random (). I wonder why this is and how to prevent it? Thank you for your help!

+4
source share
4 answers

It seems you have a problem later in the code ... (e.g. when collecting statistics). Check out this little snippet:

import random, collections
data = collections.defaultdict(int)
for x in range(1000000):
    data[round(random.random(),1)] += 1
print(data)

, 0 1, , , .

, :

defaultdict(<class 'int'>,
            {0.4: 100083,
             0.9: 99857,
             0.3: 99892,
             0.8: 99586,
             0.5: 100108,
             1.0: 49874,     # Correctly about half the others
             0.7: 100236,
             0.2: 99847,
             0.1: 100251,
             0.6: 100058,
             0.0: 50208})    # Correctly about half the others
+3

. :

50k 0 1

100k

0,2 0,3 , 200k, 0,3, 0,4, .

, 0.05, 0.15 .., .

+2

positions = []
for dummy_i in range(10):
    positions.append(random.randint (0, 10) / 10)
0

, Numpy :

import numpy as np
positions = np.random.random(10000)
positions = np.round(positions, decimals=3)
0

Source: https://habr.com/ru/post/1620537/


All Articles