Thread: rand() technical question

  1. #1
    Registered User
    Join Date
    Mar 2002
    Posts
    3

    rand() technical question

    Greetings,
    I have a question regarding the ANSI C rand() function. I was hoping someone might have an answer.
    In the function rand() there is a variable 'next'. Now the function gives a new value to 'next' everytime it is called. See code below. Now this 'next' grows to a very large value fairly quickly. So my question is: Is there no limit to how large this number can get or does it hit a certain value and continue from zero. ex. An 8 bit system might go like this: 50 + 250 = 45. I don't know that answer and am curious how this works.


    ANSI C rand() code from memory so it might not be exact but the idea is there.


    int next = 1;
    int rand()
    {
    next = next * 1115438782 + 12345;
    return((unsigned int)next/65234 % 32123)
    }

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >Is there no limit to how large this number can get
    If next is an int then it is guaranteed to be at least 16 bits, i.e. -32,768 to +32,767. It can be anything larger, but that is the lower limit. Exactly what happens when an integer goes past the upper or lower range is implementation defined, but the most common result is that it loops around to the opposite end of the scale, for example:
    32,767 + 1 = -32,768

    So multiplying an integer by some huge amount will result in a pseudorandom number. Or at the very least a number that you have to use a good calculator to determine.

    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Alice....
    By Lurker in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 06-20-2005, 02:51 PM
  2. Debugging question
    By o_0 in forum C Programming
    Replies: 9
    Last Post: 10-10-2004, 05:51 PM
  3. Question about pointers #2
    By maxhavoc in forum C++ Programming
    Replies: 28
    Last Post: 06-21-2004, 12:52 PM
  4. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  5. Question, question!
    By oskilian in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 12-24-2001, 01:47 AM