0
点赞
收藏
分享

微信扫一扫

拒绝采样例题

驚鴻飛雪 2022-03-15 阅读 75

题目链接
在这里插入图片描述

int rand10() 
{
    while (true) 
    {
        int x = (rand7() - 1) * 7 + (rand7() - 1);
        if (x >= 0 && x <= 39) 
            return x % 10 + 1;
    }
}

不均匀硬币,产生等概率的问题

在这里插入图片描述

int coin_new() 
{
    while (true) 
    {
        int a = coin();
        if (coin() != a) 
        	return a;
    }
}

均匀硬币,产生不等概率问题

P(0) = 1/4,P(1) = 3/4

int coin_new() 
{
	int a=coin();
	int b=coin();
	if(a==0&&b==0)
		return 0;
	return 1;
}

P(0) = 1/3,P(1) = 2/3

int coin_new() 
{
	while(true)
	{
		int a=coin() 
		int b=coin() 
		if(a&&b)
			return 0;
		if(a||b)
			return 1;
	}
}

## P(0) = 0.3,P(1) = 0.7

int coin_new() 
{
    while (true) 
    {
        int x = 0;
        for (int i = 0; i < 4; i++) {
            x = (x << 1) + coin();
        }
        if (x <= 2)
         return 0;
        if (x <= 9)
         return 1;
    }
}

Rand7 生成 Rand10

int rand10() 
{
    while (true) 
    {
        int x = (rand7() - 1) * 7 + (rand7() - 1);
        if (x >= 0 && x <= 39) 
            return x % 10 + 1;
    }
}

优化

int rand10() 
{
    while (true) 
    {
        int x = (rand7() - 1) * 7 + (rand7() - 1);
        if (x >= 1 && x <= 40) 
        	return x % 10 + 1;
        x = (x % 40) * 7 + rand7();
        if (x <= 60) 
        	return x % 10 + 1;
        x = (x%61) * 7 + 7;
        if (x <= 20) 
        	return x % 10 + 1;
    }
}
举报

相关推荐

for循环例题

连接被拒绝

0 条评论