c - 如何根据概率定义rand()?

标签 c random posix probability ansi-c

我有一个袋子,里面有三个相等的球。我编写了代码来模拟每个球脱落的次数(到目前为止它工作完美)。

代码

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#include <string.h>

#define N 50 /* Number of simulations*/
#define P 3  /* Number of of balls*/

unsigned long long millitime2(){
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return (unsigned long long)(tv.tv_usec);
}

int main() {
    int i;
    int num = 0;
    int *v;
    if((v = malloc(N*sizeof(int))) == NULL){
        printf("\n\tMEMORY ERROR");
        exit(1);
    }
    memset(v,0,N);
    printf("\nexpected freq: %f\n\n", ((float)1/(float)P)*100);

    for (i=0; i<N; i++){
        srand(millitime2());
        num = (rand()%P);
        v[num]++;
    }
    for(i=0;i<P;i++){
        printf("ball:%d   picked:%d/%d   freq:%f\n",i+1,v[i],N,((float)v[i]/(float)N)*100);
    }
    printf("\n");
    return 0;
}

但现在我正在做的研究需要三个球;一个球是蓝色的,两个球是白色的。

我必须在 rand() 行中进行哪些更改,以便它三次吐出一个蓝球 (~33%),三分之二吐出一个白球( ~66%)?

最佳答案

int x = rand() % 3;

x 将选择 0 到 2 之间的“随机”数字

如果 x <= 1 则为白色 ( 66%) 如果 x == 2 则蓝色 ( 33%)

关于c - 如何根据概率定义rand()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16487078/

相关文章:

java - Java 中的 SecureRandom 安全种子

java - Java/Groovy 中的 Python uniform() 替代方案(生成随机 float )

c - EACCES 和 EPERM 之间的区别

c - 是否可以使用共享对象构造函数来设置库搜索路径?

c - 将套接字绑定(bind)到网络接口(interface)

c - 如何使用 autotools 正确设置 GLib 测试框架

c - 退出函数时无法维护保存在二维字符数组中的字符串

c - C中scanf和scanf_s的区别

c# - 随机数在不同进程中与相同的 .Net 代码发生冲突

c - 为什么 pthread_equal 是线程安全的?