We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,483 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

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,

3
Contributors
2
Replies
6 Hours
Discussion Span
1 Year Ago
Last Updated
3
Views
L0s3r
Newbie Poster
14 posts since Mar 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 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,740 posts since Dec 2006
Reputation Points: 1,236
Solved Threads: 320
Skill Endorsements: 11

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
681 posts since Nov 2008
Reputation Points: 760
Solved Threads: 138
Skill Endorsements: 0

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0641 seconds using 2.82MB