Search code examples
pythonrandomroundingrounding-error

Python: rounding error distorts uniform distribution


I need to sample 10 uniformly 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 putting the result into a histogram the result looks as follows:

Frequency of numbers rounded to 1 decimal place

So the rounding seems to destroy the uniform distribution generated by random.random(). I wonder what causes this and how to prevent this from happening. Thanks for your help!


Solution

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

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

    You will see that 0 and 1 of course have about half of the samples of the other values that are all pretty much uniform.

    For example I got:

    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