Thread: generating random numbers within a range

  1. #1
    Registered User
    Join Date
    Sep 2001
    Posts
    2

    Question generating random numbers within a range

    Hello Everyone

    I'm hoping smeone can help me here - I can't see the wood for the trees. I have a requirement to generate random numbers of all types, optionally between a range. I'm OK with integer and smaller numbers, in fact the code I wrote is extremely similar to the stuff on the FAQ. Where I come unstuck is generating doubles, floats and long longs between ranges as % seems to do some truncation. I have tried something like this...

    r=(drand48()*(end-start+1))+start;

    when end and start can be the end and start of the range, or DBL_MIN and DBL_MAX.

    When I do this I don't seem to get a good spread of values, or maybe I'm just misinterpreting the output.

    Can anyone enlighten me?

    Many thanks in advance

    tucky

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    I wonder what your teacher will think if you hand in this
    Code:
    #include <stdio.h> 
    #include <stdlib.h> 
    #include <time.h>   
    
    double rand_mid(int low, int high)
    {
       return (double)(low+rand()%(high-low+1));
    }
    
    int main(void)
    {
      double x;
      int i;
      srand(time(NULL));
      for(i=0; i<10; i++){
        x = rand_mid(1, 100);
        printf("A random number from 0 to 99.9: %f\n", x);
      }
    return 0;
    }
    It's a normal integer rand() generator, except the output is a double ;p I actually haven't had a need to create random doubles or floats, I'll have to give this some thought.

    -Prelude
    Last edited by Prelude; 09-14-2001 at 11:02 AM.

  3. #3
    Registered User
    Join Date
    Aug 2001
    Posts
    101
    Code:
    #include <stdlib.h>
    
    inline double drand(double low, double high)
    {
        return ((double)rand() * (high - low)) / (double)RAND_MAX + low;
    }
    Of course, this limits you to a maximum of RAND_MAX numbers between low and high.
    - lmov

  4. #4
    Registered User
    Join Date
    Sep 2001
    Posts
    2
    Teacher? This is for a utility at work.

    I'll give the code a try - thanks for the help

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Generatin Random Numbers
    By dantu1985 in forum C Programming
    Replies: 15
    Last Post: 08-13-2007, 01:21 AM
  2. Replies: 7
    Last Post: 09-26-2005, 05:09 PM
  3. Need Help Generating Random Numbers In C++
    By slickwilly440 in forum C++ Programming
    Replies: 11
    Last Post: 09-18-2005, 01:38 PM
  4. random numbers
    By ballmonkey in forum C++ Programming
    Replies: 3
    Last Post: 01-18-2005, 02:16 PM
  5. Generating random numbers WITHOUT duplicates
    By fake1 in forum C++ Programming
    Replies: 3
    Last Post: 02-09-2002, 08:14 PM