1 Replies - 1141 Views - Last Post: 28 March 2010 - 07:00 AM Rate Topic: -----

#1 Guest_helphelphelp*


Reputation:

How to generate N real random values in the interval [0 20]?

Posted 28 March 2010 - 06:45 AM

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 =)
Is This A Good Question/Topic? 0

Replies To: How to generate N real random values in the interval [0 20]?

#2 NickDMax   User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2255
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

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!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1