1. 拒绝采样
在解LC-470前先介绍一道拒绝采样的经典问题:利用频率近似概率的方式求出 π 的值。在 1×1 的方块内随机坐标采样,记录落入以原点为圆心,半径为1的 41 圆内的次数。
由 41πr2=Ncnt 可得 π=N×r24×cnt ,由于 r=1 ,所以 π=N4×cnt
1 2 3 4 5 6 7 8 9 10 11
| int main() { srand((unsigned)time(0)); int N = (int)1e7, cnt = 0; for (int i = 0; i < N; i++) { double a = (1.0 * rand() / RAND_MAX); double b = (1.0 * rand() / RAND_MAX); if (a * a + b * b < 1.0) cnt++; } printf("%lf", (4.0 * cnt) / N); return 0; }
|
2. LC-470 Rand7生成Rand10
力扣高赞题解
(rand_X() - 1) × Y + rand_Y() ==> 可以等概率的生成[1, X * Y]范围的随机数
1 2 3 4 5 6 7 8 9 10 11
| class Solution { public: int rand10() { while(true){ int num = (rand7()-1)*7 + rand7(); if(num <= 40) return num % 10 + 1; } } };
|