NO

Author Topic: Single Random Number in Limited Range  (Read 3055 times)

zk52959

  • Guest
Single Random Number in Limited Range
« on: February 26, 2008, 09:21:36 PM »
I have a situation where I need to get a random number once-only during the execution of a (very short and simple) program.  I am using the following function:


/* ============================= randTarget ================================
   This function generates a random integer between 1 and 20.
      Pre:   Nothing.
      Post:   Returns the random number target.
*/

int randTarget(void)
{
// Local Declarations
   int num;

// Statements
   srand(time(NULL));

   num = rand() % 20 + 1;   

// End function
   return num;   // Return target number
} // randTarget


My problem is that each time I run the program, and get the single random number, my random number function gives me the same few numbers over and over (e.g., 4, 8, 16, 20) and some numbers never come up.

However, if I test the random number function with a test print loop (e.g., 100 iterations) the numbers appear randomly distributed then.

How can I get a (reasonably) truly random number, on a one-time-per-program-execution basis, in a limited range of numbers (e.g., integers between 1 and 20)?

Offline Robert

  • Member
  • *
  • Posts: 245
Re: Single Random Number in Limited Range
« Reply #1 on: February 27, 2008, 09:33:41 AM »
Instead of

num = rand() % 20 + 1;

use

num = (20 - 1 + 1) * (rand()/RAND_MAX) + 1

which is

num = (high - low +1) * (rand()/RAND_MAX) + 1

Robert Wishlaw

zk52959

  • Guest
Re: Single Random Number in Limited Range
« Reply #2 on: February 27, 2008, 04:42:21 PM »
Thank you, Robert.

When I first tried your suggestion, I kept getting "1", but when I added (float) to your code, it works perfectly.


    num = 20 * (float)rand() / RAND_MAX + 1;


Thank you again for the assistance.

severach

  • Guest
Re: Single Random Number in Limited Range
« Reply #3 on: February 28, 2008, 03:30:04 AM »
Code: [Select]
    num = 20.0 * rand() / RAND_MAX + 1;
Rather than cast I like to put a decimal into the number and let the compiler pick what size it's supposed to be.

zk52959

  • Guest
Re: Single Random Number in Limited Range
« Reply #4 on: March 02, 2008, 08:32:02 PM »
Good idea.  Thanks!