Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randint doesn't always follow uniform distribution

Tags:

python

random

I was playing around with the random library in Python to simulate a project I work and I found myself in a very strange position.

Let's say that we have the following code in Python:

from random import randint import seaborn as sns  a = [] for i in range(1000000):     a.append(randint(1,150))  sns.distplot(a) 

The plot follows a “discrete uniform” distribution as it should.

Range betwee 1 and 150

However, when I change the range from 1 to 110, the plot has several peaks.

from random import randint import seaborn as sns  a = [] for i in range(1000000):     a.append(randint(1,110))  sns.distplot(a) 

Range from 1 to 110

My impression is that the peaks are on 0,10,20,30,... but I am not able to explain it.

Edit: The question was not similar with the proposed one as duplicate since the problem in my case was the seaborn library and the way I visualised the data.

Edit 2: Following the suggestions on the answers, I tried to verify it by changing the seaborn library. Instead, using matplotlib both graphs were the same

from random import randint import matplotlib.pyplot as plt  a = [] for i in range(1000000):     a.append(randint(1,110))  plt.hist(a)  

From matplotlib

like image 346
Tasos Avatar asked Dec 12 '16 11:12

Tasos


1 Answers

The problem seems to be in your grapher, seaborn, not in randint().

There are 50 bins in your seaborn distribution diagram, according to my count. It seems that seaborn is actually binning your returned randint() values in those bins, and there is no way to get an even spread of 110 values into 50 bins. Therefore you get those peaks where three values get put into a bin rather than the usual two values for the other bins. The values of your peaks confirm this: they are 50% higher than the other bars, as expected for 3 binned values rather than for 2.

Another way for you to check this is to force seaborn to use 55 bins for these 110 values (or perhaps 10 bins or some other divisor of 110). If you still get the peaks, then you should worry about randint().

like image 181
Rory Daulton Avatar answered Sep 20 '22 21:09

Rory Daulton