rand() issue

This is a discussion on rand() issue within the C Programming forums, part of the General Programming Boards category; Hi, I'm trying to generate a random number betwen any numbers (eg from 1 to 100) in C and I've ...

  1. #1
    Registered User
    Join Date
    Aug 2007
    Posts
    52

    rand() issue

    Hi, I'm trying to generate a random number betwen any numbers (eg from 1 to 100) in C and I've tried this code:
    Code:
    #include<stdio.h>
    #include<math.h>
    #include<time.h>
    #include <stdlib.h>
    int NumAleatori(int max)
    {
    int num;
    num=((int)ceil(((double)rand()/RAND_MAX)*(max+1)))%(max+1);
    return num;
    }
    void main ()
    {
    int N,a;
    srand( (unsigned)time( NULL ) );
    printf(“Enter an integer:\”);
    scanf(“%d”,&N);
    a = NumAleatori(N);
    printf(“%d”,a);
    
    }
    It does not give me random numbers. It gives me always the same number for small ranges and it follows a pattern for a graters ranges.
    Do you know how can I easily solve this?
    thanks in advance!

  2. #2
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Katy, Texas
    Posts
    2,309
    Read the FAQ for all the info you would ever want on this topic.
    Mac and Windows cross platform programmer. Ruby lover.

    Quote of the Day
    12/20: Mario F.:I never was, am not, and never will be, one to shut up in the face of something I think is fundamentally wrong.

    Amen brother!

  3. #3
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    While scoping out the FAQ check out the thread about using [code] tags and proper indentation. One without the other is basically the same as neither (particularly when considering that no code-tags will just truncate all your whitespace).

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Code:
    int NumAleatori(int max)
    {
    int num;
    num=((int)ceil(((double)rand()/RAND_MAX)*(max+1)))%(max+1);
    return num;
    }
    That's very complicated, compared to what you actually need.

    You may also find a lot of useful info here:
    http://eternallyconfuzzled.com/jsw_home.aspx

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  5. #5
    Registered User
    Join Date
    Aug 2007
    Posts
    52
    Read the FAQ for all the info you would ever want on this topic.
    This code is in cprogramming FAQs:

    Code:
    /*
     * This code is written in C, but it could just as easily be done in C++.
     * The rand() and srand() functions are available in both languages.
     */
     
    #include <stdio.h>  
    #include <stdlib.h>  
    #include <time.h>  
    
    int main(void)
    {
      int i;
      
      srand(time(NULL));
      
      i = rand();
      
      printf ("Your random number is %d\n", i);  
    
      printf ("This compiler can generate random numbers from 0 to %d\n", RAND_MAX);
    
      return(0);
    }
    When I compile it in my compiler (dev-c++), it gives numbers following a pattern: 22410, 22469, 22518, 22576, 22616...
    I use win xp sp3.
    Thanks!

  6. #6
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    The first random number generated by this program is based on the system time -- so if you run it repeatedly, without much time in between, the numbers you get won't get very far from each other.

  7. #7
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Yes, because the difference in "time()" between two calls close together is really not very big.

    rand() is like drawing cards out of a shuffled deck. The deck is always shuffled in exactly the same way (imagine you build a machine to shuffle decks, and it does this so "perfectly" that every time you do it, the deck comes out shuffled the same order). What srand() does is to "cut the deck", so that we start taking cards from the "cut point". But from that point, we always get the same sequence (try writing a program that asks for a number, and use that as a seed, then print 5 random numbers using rand(), and restart your program and use the same number again.

    However, if you enter some fairly large number that is ALMOST the same each time, you will notice that you get numbers that are "similar but not the same" each set of 5 (and the second and third number probably isn't as close to the corresponding numbers as the first one was), because we are now in a different place in the deck.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  8. #8
    Registered User
    Join Date
    Aug 2007
    Posts
    52
    Code:
    The first random number generated by this program is based on the system time -- so if you run it repeatedly, without much time in between, the numbers you get won't get very far from each other.
    So what to do if you want two different random numbers in the same program?

  9. #9
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    As I explained, srand() sets where in the sequence of numbers ("the shuffled deck") you start. From there on, it will generate "random" numbers, so the next number will be quite different from the one previously picked. Just like if you shuffle a deck, if you draw queen of spades, the next one will (assuming you have shuffled properly) very likely be something other than king of spades.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  10. #10
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by JOCAAN View Post
    So what to do if you want two different random numbers in the same program?
    Use another seed. If you want a single function I suppose you could use rand() to get a seed for another rand(), which might mix it up more.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  11. #11
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Quote Originally Posted by JOCAAN View Post
    Code:
    The first random number generated by this program is based on the system time -- so if you run it repeatedly, without much time in between, the numbers you get won't get very far from each other.
    So what to do if you want two different random numbers in the same program?
    Keep typing rand(). Over and over and over again.

  12. #12
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by MK27 View Post
    Use another seed. If you want a single function I suppose you could use rand() to get a seed for another rand(), which might mix it up more.
    It works just as well to call rand() twice in a row to get two different random numbers. Anything else is likely to just make it LESS random [there was a thread on that subject some time ago, where someone wanted to use srand() with a different pseudo-random number generator, and the conclusion was that "it just makes it worse".

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  13. #13
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    There are random number protocols if you need something truly random. Otherwise rand() is sufficient enough for all your randomization needs without adding a bunch of superfluous steps that make an entire block of numbers be regenerated.

  14. #14
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by master5001 View Post
    There are random number protocols if you need something truly random. Otherwise rand() is sufficient enough for all your randomization needs without adding a bunch of superfluous steps that make an entire block of numbers be regenerated.
    Regular "rand" is probably good enough for most hobby projects. If you are making a professional poker game where people actually play with and win REAL money (electronic or paper ones) you obviously will want something that can not be predicted, and rand() isn't quite good enough for that. But for a simple game or basic "flip a coin 200 times" type application, it will be fine.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  15. #15
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    Agreed. But statements such as:

    Code:
    int x, y;
    
    srand(time(NULL));
    
    for(x = 0, y = rand(); x < y; ++x)
      x = rand();
    
    srand(x);
    "This is way better than just a regular seed! Its a randomly randomized random seed!"

    Are more or less guided by the misconception that rand() is not good enough. Which it is. The whole idea behind seeds isn't to yank your chain, its just to make a program exhibit predictable behavior.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21