Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

应知应会C++小技巧——C++随机数的生成的疑惑点 #60

Open
Enemy-77 opened this issue Oct 28, 2024 · 2 comments
Open

应知应会C++小技巧——C++随机数的生成的疑惑点 #60

Enemy-77 opened this issue Oct 28, 2024 · 2 comments

Comments

@Enemy-77
Copy link

image
这个地方的概率是什么意思鸭?没有明白呢,感觉像是少写了一部分数字?这两个概率是怎么得出的呢?

@archibate
Copy link
Contributor

archibate commented Nov 26, 2024

为了你简单理解,假如RAND_MAX=11
那么rand()可能生成0,1,2,3,4,5,6,7,8,9,10,11
对其取10的模后,0和10都能得到0,11和1都能得到1
rand() % 10可能生成0,1,2,3,4,5,6,7,8,9,0,1
有两种可能都能生成0和1,这就导致0和1的出现概率变成了2到9之间数字出现概率的两倍,概率分布就不均匀了。

同理,RAND_MAX=32767时,会导致0到6之间的数字出现概率略高,对于严格要求随机数均匀性的场景就不合适了。
特别是用rand() % 10000生成10000以内随机数时更明显,范围越大越明显。

@longlongvip
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants