I am a starter of the program C++. I need to sort N values in decending order. However, I am not sure how to generate N real random values from 0 to 20. I deeply appreciate any help received =)
1 Replies - 1141 Views - Last Post: 28 March 2010 - 07:00 AM
#1 Guest_helphelphelp*
How to generate N real random values in the interval [0 20]?
Posted 28 March 2010 - 06:45 AM
Replies To: How to generate N real random values in the interval [0 20]?
#2
Re: How to generate N real random values in the interval [0 20]?
Posted 28 March 2010 - 07:00 AM
Well RAND_MAX is the largest value returned by the rand() function.
20 * (RAND_MAX/RAND_MAX) = 20
20* (0/RAND_MAX) = 0
and if X >= 0 and X <= RAND_MAX then if:
Y = 20 * (X / RAND_MAX)
then Y >= 0 and Y <= 20
More generally:
if X >= 0 and X <= RAND_MAX then if:
Y = (max - min) * (X / RAND_MAX) + min
then Y >= min and Y <= max
So X = rand() will give you a number between 0 and RAND_MAX, dividing that number by RAND_MAX will map that number to a value between 0 and 1, multiply that by your range will give you a value between 0 and max_range, then add in you minimum will give you a value between min and max.
make sure you are dealing with floating point arithmetic when you do the division though!
20 * (RAND_MAX/RAND_MAX) = 20
20* (0/RAND_MAX) = 0
and if X >= 0 and X <= RAND_MAX then if:
Y = 20 * (X / RAND_MAX)
then Y >= 0 and Y <= 20
More generally:
if X >= 0 and X <= RAND_MAX then if:
Y = (max - min) * (X / RAND_MAX) + min
then Y >= min and Y <= max
So X = rand() will give you a number between 0 and RAND_MAX, dividing that number by RAND_MAX will map that number to a value between 0 and 1, multiply that by your range will give you a value between 0 and max_range, then add in you minimum will give you a value between min and max.
make sure you are dealing with floating point arithmetic when you do the division though!
Page 1 of 1

New Topic/Question
Reply
MultiQuote






|