Hi Guys.

Random no.'s always bother me.So,I want to start a discussion over their uniform distribution.

Given : rand5() which generates randomly distributed no. from 1-5.
To Code: rand7() which generates randomly distributed no. from 1-5.

You have to give code using rand5() as well as without using it.


5 Years
Discussion Span
Last Post by StuXYZ

If we call rand5() seven times and add up the results, we would get an integer in the inclusive interval [7,35].
Divide this number by 5.0 and we would get a real number in the inclusive interval [1.0,7.0].

Take care of the round-off correctly (how?) and you have rand7().


First off given your question statement,

To Code: rand7() which generates randomly distributed no. from 1-5

you can do this: ;)

int rand7() {  return rand5(); }

Ok I guess that isn't your question, you actually want to return rand7 where the result is 1-7.

First thing to establish is if rand5() returns an integer value or a floating point number in the rand 1-5. If it is integer you can try this:

Quicker in the long run is to use a reduction algorithm. E.g create the number

while(a>20) {
return 1+a/7;

The issue is is it quicker than adding 7 numbers (and seven calls to rand5()). It can be slower, but most of the time it is quicker.

If on the other hand you have 1.0->5.0 you can actually use the same algorithms, but in that case there is the much quicker approach of just dividing the result, however, this approach looses low bit accuracy.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.