Thread: Generating a random real number

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    33

    Generating a random real number

    I was wondering how to generate a random REAL number within an array.

    I always generate an error with this equation

    n = 20.2 + rand() % 33.3

    due to the fact, I believe, that the modulus operator does not work with real numbers.
    Last edited by aromash; 11-20-2010 at 04:57 PM.

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    You're correct. So I gather you're looking for a random number between 20.2 and 53.5? Try something like
    Code:
    float   r;
    
    r = ((float) rand() / RAND_MAX);    // generate a random value between 0 and 1
    r *= 33.3;    // scale this up to the range you want
    r += 20.2;    // slide the range up to the starting value you want
    
    r = 20.2 + 33.3 * ((float) rand() / RAND_MAX);   // same thing, in one line

  3. #3
    Registered User
    Join Date
    Oct 2010
    Posts
    33
    those numbers are just arbitrarily chosen numbers just to prove a point. I'll try that formula out, thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help generating multiple random numbers
    By d-dub in forum C++ Programming
    Replies: 7
    Last Post: 10-30-2006, 01:00 PM
  2. Logical errors with seach function
    By Taka in forum C Programming
    Replies: 4
    Last Post: 09-18-2006, 05:20 AM
  3. Counting number from a random file
    By kamisama in forum C Programming
    Replies: 42
    Last Post: 02-22-2005, 05:16 PM
  4. non repeating random number generation?
    By gencor45 in forum C# Programming
    Replies: 1
    Last Post: 02-08-2005, 05:23 PM
  5. How do I restart a random number sequence.
    By jeffski in forum C Programming
    Replies: 6
    Last Post: 05-29-2003, 02:40 PM