This project is inspired by 3Blue1Brown. When I watch the But what is the Central Limit Theorem?, I notice the dice example is a good trial for programming to "draw" a normal distribution curve. So I wrote C++ codes and use PPM format image to prove it and try more probability to draw diffderent images. The results of different conditions like magic of nature and math. I want more people to be able to use computer to see the "magic" by themselves.
If you can read Chinese, there is a blog to describe the details and some trials (two URL are same, choose which you can fast access):
- My Blog Site URL: "Verify the central limit theorem using C++"
- CSDN URL: 《使用 C++ 验证非均匀概率的离散事件在样本数量足够大时,符合正态分布曲线(通过生成一个PPM格式的图像)》
Please choose your language to view according url.
If you are curious about the meaning of some codes, you can read the blog, the comments of code will answer your question. If you can't read Chinese and you don't trust the auto-tranlate, please ask me.
The size of PPM image control by width
and height
in line 28-19. If you change how many times added, the number of trail samples or probability, you should change the size to display entire chart.
In line 51 you can change the number of times added.
In line 48 you can change the number of trail samples.
In source code, there is an array a[]
control probability of different elements. By default, the a[]
is {1, 2, 3, 4, 5, 6}
, it means each element have same probability, 1/6.
If you change the array, the probability of elements will change. For example, if the array is {1, 2, 3, 4, 5, 6, 6, 6, 6, 6}
, the probability of 6
is 1/2 (5/10), probability of other elements is 1/10. I leave a extreme situation in comment, the probability of 1
is 0.95 and others are 0.01, you can try it. The image will be like:
After setting, you can run this command:
$ g++ pclt.cpp && ./a.out
It will generate a PPM image called output-image.ppm
. The directory will be like:
You can see a nice image of normal distribution curve.
If you want to use codes and contents outside of education or personal usage (including blog), please credit the original.