由于rand() 为您提供介于0 和RAND_MAX 之间的值,您只需选择适当的阈值即可获得特定百分比的值。例如,如果 RAND_MAX 是 999,则预计所有值的 42% 将小于 420。
因此您可以使用以下完整程序中的代码来设置适当的阈值并测试您的值的分布:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
int main(int argc, char *argv[]) {
// Get threshold (defaults to ~PI%), seed random numbers.
double percent = (argc > 1) ? atof(argv[1]) : .0314159;
int threshold = round(RAND_MAX * percent);
srand(time(0));
// Work out distribution (millions of samples).
int below = 0, total = 0;
for (int i = 0 ; i < 1000000; ++i) {
++total;
if (rand() < threshold) ++below;
}
// Output stats.
printf("Using probability of %f, below was %d / %d, %f%%\n",
percent, below, total, below * 100.0 / total);
}
一些样本运行,具有不同的期望概率:
Using probability of 0.031416, below was 31276 / 1000000, 3.127600%
Using probability of 0.031416, below was 31521 / 1000000, 3.152100%
Using probability of 0.421230, below was 420936 / 1000000, 42.093600%
Using probability of 0.421230, below was 421634 / 1000000, 42.163400%
Using probability of 0.175550, below was 175441 / 1000000, 17.544100%
Using probability of 0.175550, below was 176031 / 1000000, 17.603100%
Using probability of 0.980000, below was 979851 / 1000000, 97.985100%
Using probability of 0.980000, below was 980032 / 1000000, 98.003200%
Using probability of 0.000000, below was 0 / 1000000, 0.000000%
Using probability of 1.000000, below was 1000000 / 1000000, 100.000000%
因此,底线是:要满足您对概率为 p(double 值)和概率为 1 - p 的零的愿望,您需要以下内容:
srand(time(0)); // done once, seed generator.
int threshold = round(RAND_MAX * p); // done once.
int oneOrZero = (rand() < threshold) ? 1 : 0; // done for each cell.
请记住rand() 的限制,(例如)概率0.0000000000 和0.0000000001 之间的差异很可能不存在,除非RAND_MAX 大到足以产生影响。我怀疑你是否会使用这么好的概率,但我想我最好提一下以防万一。