LLN - Testing Law of Large Numbers with Python

LLN - Testing Law of Large Numbers with Python

I am back in Python for Data Science studies, and this week I am trying to learn more about the Law of Large Numbers.

I am wondering if someone could help me to improve better tests using Python. In the meantime, I want to share a simple code using Python to test the LLN theory.

LLN is a fundamental concept in statistics, which says that the average results obtained from many trials should be close to the expected value and tend to become closer to them as we perform more trials.

N?o foi fornecido texto alternativo para esta imagem

Even though the LLN is a fundamental concept, I would try to make a code to check if it is true.

I take advantage of the RANDN() function from NumPy. This function returns an aleatory number based on a normal distribution.

I created a simple loop to generate a lot of random numbers, started with 10 numbers, and increased it to 10 million.

Inside the loop, if the random number was between -1 and 1, I counted it. 

At the end of the loop, I made the division of these numbers between -1 and 1, and the total numbers.

from numpy.random import randn


#randon numbers  
total = 10

#counter
counter = 0
for i in range(0, total):
    number = randn()
    if 1>= number >= -1:
        counter = counter+1
print ("average = ",counter/total)


As it is a normal function, the expected result is 68,2%.

N?o foi fornecido texto alternativo para esta imagem

Above you can see the results of the tests using a Jupyter Notebook:

When we increase the number of random numbers, the code result test becomes closer and closer to the expected result. 

The code is on my GitHub profile. Please feel free to use it.


Mariana Mazullo

Yoga Instructor @ District of Saanich | Kinesiology, Yoga Instruction

2 年

Wow!! Great job!!

回复

要查看或添加评论,请登录

Alex Mazullo的更多文章

社区洞察

其他会员也浏览了