How to generate a random number with equal probabi

2019-06-12 07:32发布

I tried a lot but could not get a solution for this problem

Function returns numbers in range [1,6] with equal probability. You can use library's rand() function and you can assume implementation of rand() returns number in range number in range [0,RAND_MAX] with equal probability.

2条回答
闹够了就滚
2楼-- · 2019-06-12 08:00

We'll do this in multiple steps.

You need to generate a number in the range [1, 6], inclusive.

You have a random number generator that will generate numbers in the range [0..RAND_MAX].

Let's say you wanted to generate numbers in the range [0..5]. You can do this:

int r = rand();  // gives you a number from 0 to RAND_MAX
double d = r / RAND_MAX;  // gives you a number from 0 to 1
double val = d * 5; // gives you a number from 0 to 5
int result = round(d);  // rounds to an integer

You can use that technique to So given a range of [0, high], you can generate a random number, divide by RAND_MAX, multiply by high, and round the result.

Your range is [1, 6], so you have to add another step. You want to generate a random number in the range [0, 5], and then add 1. Or, in general, to generate a random number in a given range, [low, high], you write:

int r = rand();
double d = r / RAND_MAX;
int range = high - low + 1;
double val = d * range;
result = round(val);

Obviously you can combine some of those operations. I just showed them individually to illustrate.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-06-12 08:08

Basically you are looking for using the operator% (modolus).

r = rand() % 6 + 1

If you are afraid that RAND_MAX % 6 != 0 and the solution will be biased - you just need to 'throw' some numbers (up to 5) out and redraw if you get them:

let M = (RAND_MAX / 6) * 6 [integer division]
r = dontCare
do { 
   r = rand()
} while (r > M)
r = r % 6 + 1 

PS, if you want to draw a 'real' number, it can be done with:

r = drawInt(1,5) // draw integer from 1 to 5 inclusive, as previously explained.
r += rand() / (RAND_MAX - 1) //the decimal part

Note that it is not a 'real' number, and the density between two numbers is 1/RAND_MAX-1

查看更多
登录 后发表回答