求算法,已知整数随机函数rand(0,1),如何变化成rand(0,2)

问题描述:

求算法,已知整数随机函数rand(0,1),如何变化成rand(0,2)
已知整数随机函数x=rand(0,1)
其中 x=0的概率是1/2,x=1的概率是1/2
现在要求y=rand(0,2)
其中 y=0的概率是1/3,y=1的概率是1/3,y=1的概率是1/3
如何用rand(0,1)表示出rand(0,2)?
其中 y=0的概率是1/3,y=1的概率是1/3,y=2的概率是1/3
1个回答 分类:综合 2014-10-12

问题解答:

我来补答
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
 
/* rand(0, 1) */
int rand1(){
return rand()%2;
}
 
/* rand(0, 2) */
int rand2(){
int r;
do{
r = 2*rand1() + rand1();
}while(r >= 3);
return r;
}
 
int main(){
int i, A[3] = {0, 0, 0};
 
srand((unsigned)time(NULL));
for(i=0; i<10000; i++)
A[rand2()]++;
printf("%g %g %g", A[0]/10000., A[1]/10000., A[2]/10000.);
}参考自:
"http://stackoverflow.com/questions/137783/expand-a-random-range-from-15-to-17"
 
 
展开全文阅读
剩余:2000
上一页:dc2inr3qec3r2
下一页:这样怎么写