如何编码获得p次1和(1-p)次0? [英] How do I code to get p times 1 and (1-p) times 0?
问题描述
使用C ++随机数生成器rand(),实现一个偏差硬币,输出1概率为p,0概率为1-p。不要在你将要实现的功能中播种随机数生成器!
我尝试过:
我试过这个来生成0和1:
float output = rand()%2;
Using the C++ random number generator rand(), implement a biased coin that outputs 1 with probability p and 0 with probability 1–p. Do not seed the random number generator within the function you will be implementing!
What I have tried:
I have tried this to generate 0 and 1:
float output=rand()%2;
推荐答案
仔细阅读问题:它需要您生成一个偏置硬币:一个返回0比1更多的硬币,反之亦然,取决于 p <给出的概率/ code>
因此,您需要使用的值,而不是使用2直接50:50 p
偏向你的结果。由于 p
是0到1之间的浮点值,而 rand
总是返回一个整数,你将不得不偷偷摸摸。
我首先做两个测试:p = 0(在这种情况下返回0)和p = 1(在这种情况下返回1)。如果它们都失败了,那么生成一个随机数并将其乘以p。如果结果大于最大值的一半 rand
可以在系统中返回,则返回1,否则返回0.
但这是你的作业,不是我的作业 - 所以我不会给你任何代码!
Read the question carefully: it requires you to produce a BIASED coin: one that returns more 0's than 1's or vice versa, dependent on the probability given inp
So, instead of using 2 which gives you a straight 50:50, you need to use the value ofp
to bias your results. Sincep
is a floating point value between 0 and 1 andrand
always returns an integer, you are going to have to get sneaky.
I'd start by doing two tests: p = 0 (in which case return 0) and p = 1 (in which case return 1). If they both fail, then generate a random number and multiply it by p. If the result is greater than half the maximum valuerand
can return in your system then return a 1, otherwise return a 0.
But this is your homework, not mine - so I'll give you no code!
1)选择你的语言。
2)研究兰德是如何用这种语言工作的。
1) Choose your language.
2) study how rand is working in that language.
实现一个有概率为p的输出1的偏置硬币0概率为1-p。
implement a biased coin that outputs 1 with probability p and 0 with probability 1–p.
这个重要的词是有偏见的。这意味着两步绘图。
假设赔率为0.33和0.67。
- 抽取一个随机数
- 随机查看赔率并决定结果。
我们不做你的家庭作业。
所以只是提示一些。
the important word is 'biased'. This imply a 2 step drawing.
Say the odds are 0.33 and 0.67.
- draw a random number
- check the random against odds and decide of the result.
We do not do your HomeWork.
So just a few hints.
>
这篇关于如何编码获得p次1和(1-p)次0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!