954,504 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Code a function rand7() when we're given rand5() .

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.


Thanks,

L0s3r
Newbie Poster
14 posts since Mar 2011
Reputation Points: 10
Solved Threads: 0
 

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().

vijayan121
Posting Virtuoso
1,606 posts since Dec 2006
Reputation Points: 1,159
Solved Threads: 287
 

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) {
  a=(rand5()-1)*5+(rand5()-1);
}
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.

StuXYZ
Practically a Master Poster
680 posts since Nov 2008
Reputation Points: 760
Solved Threads: 138
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: