CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Nov 2004
    Posts
    20

    random number generator

    I would like to know if there is a library function which can generate random integers in a specified by the user field,for example [100-150]
    If anyone knows please reply as soon as possible....

  2. #2
    Join Date
    Sep 2004
    Posts
    519

    Re: random number generator

    Assuming you want evenly distributed numbers:

    Code:
    int void f()
    {
        return rand() % 51 + 100;
    }
    Which will return a pseudo random number in the closed interval [100, 150].

    Hope this helps

    PS. The initialize the pseduo random number generator see srand()

  3. #3
    Join Date
    Nov 2002
    Location
    Foggy California
    Posts
    1,245

    Re: random number generator

    The standard C rand() function is usually not a very good random number generator. Here is a FAQ about good random number generators.

    Also, using modulo generally creates a bad set of random numbers -- they end up not being very random. (The modulo operation gives extra weight to the least significant bits of a number; and the least significant bits tend to be the least random returned from PRNGs.) A better, though slower method is to do this:

    Code:
    /* identical interface as rand(), but produces better random sequences */
    int GoodRand(); 
    
    /* returns random numbers on the interval [0, 1) -- maybe a mersenne twister */
    double GoodDblRand(); 
    
    int Rand1()
    {
        return 100 + (int) (GoodDblRand()*51.0/RAND_MAX);
    }
    
    int Rand2()
    {
        return 100 + (int) (GoodDblRand()*51);
    }
    Last edited by KevinHall; November 24th, 2004 at 02:59 PM.
    Kevin Hall

  4. #4
    Join Date
    Jun 2001
    Location
    Orlando, FL
    Posts
    232

    Re: random number generator


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured