Thread: random isn't really random?

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    May 2008
    Posts
    43

    random isn't really random?

    hi,
    Just a quick question. I wrote a short code for generating 0, 1 randomly in order to simulate a coin-tossing game.
    Code:
    //This program will simulate 100 times
    //of coin-tossings. Then it will calculate
    //the frequency how many times it's HEAD or TAIL
    #include <iostream>
    #include <iomanip>
    #include <cstdlib>
    using namespace std;
    int flip(void); //return 0 for T(tail=0) and H(head=1)
    
    int main()
    {
    	int headCount=0;
    	int tailCount=0;
    	for (int i=1; i<=100; i++) //simulate flipping 100 times
    	{
    		switch(flip())
    		{
    		case (1):
    			cout << " " << "H";
    			headCount++;
    			break;
    		case (0):
    			cout << " " << "T";
    			tailCount++;
    			break;
    		}
    		if (i%10==0)
    			cout << endl;
    	}
    	cout << "Head " << headCount << endl;
    	cout << "Tail " << tailCount << endl;
    
    	return 0;
    }
    //Function that does fliping th coin
    int flip(void)
    {
    	int outcome;
    	outcome=rand()%2;
    	return outcome;
    }
    I compiled and execute the program, it just gave out 1 result all the time!!!
    I'm wondering probably the way I use rand() is not good enough?

    thanks!

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Do you mean that you get 100 of the same result, or that every time you run the program you get the same split of heads/tails?

    The latter is expected -- the pseudo random number generator is designed to be "predictable" in this way (so that you can check that you don't break things as you're debugging). To get different numbers on different runs of the program, you need to use srand() to set a seed. (Usually you do something like srand(time(0)); this assumes that you #include time.h.)

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    May 2008
    Posts
    43
    I got the same result
    H T T T T H H H H
    T T T H H H H H H
    ......

    and the same count for each H and T for every execution...
    perhaps, I should use "srand"

  5. #5
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by azsquall View Post
    I got the same result
    H T T T T H H H H
    T T T H H H H H H
    ......

    and the same count for each H and T for every execution...
    perhaps, I should use "srand"
    Yes, if you want each time you run the code to produce different results, you should use some sort of random seed that varies from time to time.

    All of the traditional random number generators that are used by computers generate a series of numbers based on a "seed". If you start with the same seed, you get the same sequence. If you start with very similar seeds, it's likely that you get a similar result - but by no means guaranteed.

    So running your code twice in a row using time(0) as a seed may produce a very similar result, because the "time" may be close enough to produce the same result. If you wait for several seconds before running it again, then you would be more safe.

    --
    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.

  6. #6
    Registered User
    Join Date
    May 2008
    Posts
    81
    heh. welcome to the world of PRNGs.

    QRBG is the way to go http://cboard.cprogramming.com/showthread.php?t=103071

    kidding . srand(time(NULL)) would probably work ok for you, though I found that one needs to wait at least 1 second between each call, and even then the results were largely linear.

  7. #7
    Registered User guesst's Avatar
    Join Date
    Feb 2008
    Location
    Lehi, UT
    Posts
    179
    Right, you're doing flips without seeding your random. so be sure to run seed(time(NULL)) and it will change output.

    With that, dig into that faq.
    Type-ins are back! Visit Cymon's Games at http://www.cymonsgames.com for a new game every week!

  8. #8
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    You should only call srand once in your program. Once the PRNG is seeded it will generate pseudo-random numbers properly. If you keep seeding it that will throw off its mechanism.

  9. #9
    Registered User
    Join Date
    May 2008
    Posts
    81
    Quote Originally Posted by Daved View Post
    You should only call srand once in your program. Once the PRNG is seeded it will generate pseudo-random numbers properly. If you keep seeding it that will throw off its mechanism.
    like I mentioned in the QRBG post, I seeded srand() with the output of the Mersenne PRNG, and I did this for every iteration of the loop. that works very well.

  10. #10
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Yeah, but it makes no sense (I admit I didn't read your entire post in that thread or I would have mentioned it there). The point of a seed is to seed it once, it will generate a proper random number after that. If you're seeding rand every time, then your random number is based only on the Mersenne PRNG, and there isn't any random-ness derived from rand(). You might as well just use the output of the Mersenne PRNG directly.

  11. #11
    Use this: dudeomanodude's Avatar
    Join Date
    Jan 2008
    Location
    Hampton, VA
    Posts
    391
    might wanto to read this
    Ubuntu Desktop
    GCC/G++
    Geany (for quick projects)
    Anjuta (for larger things)

  12. #12
    Registered User
    Join Date
    Dec 2007
    Posts
    932
    I changed your program with srand() but i get
    "void value not ignored as it ought to be" error.

    Code:
    int flip(void)
    {  
        int outcome;
        outcome = srand ( time(0) &#37; 2 );   //error
        return outcome;
    }
    I tried to google it without success.
    Anyone please?
    Using Windows 10 with Code Blocks and MingW.

  13. #13
    Registered User guesst's Avatar
    Join Date
    Feb 2008
    Location
    Lehi, UT
    Posts
    179
    Quote Originally Posted by Ducky View Post
    I changed your program with srand() but i get
    "void value not ignored as it ought to be" error.

    Code:
    int flip(void)
    {  
        int outcome;
        outcome = rand () % 2;
        return outcome;
    }
    
    int main () {
      srand ( time(0));
      /* The rest of your program */
    }
    I tried to google it without success.
    Anyone please?
    srand doesn't generate random numbers. It seeds the random number generator. Call it at the beginning of your program before you call your rands.
    Type-ins are back! Visit Cymon's Games at http://www.cymonsgames.com for a new game every week!

  14. #14
    Registered User
    Join Date
    May 2008
    Posts
    81
    I think we have already put to rest the question as to whether rand coupling adds any value or not. It doesn't.

    I believe we have also established that multiple resetting of a prng by re-seeding with a random seed is not detrimental to the randomness of a distribution. Its simply a redundant code ovehead.

    Moving on, I will be comparing QRBG's results with Mersenne's (if I can ever get QRBG to work ). I am not interested in the program's efficiency with one implementation vs the other. The main purpose of this project was to use the program as a tool to study the manifestation of probabilities.

    So far, I've had to limit my simulation to 10,000 iterations because past that, the results screw up. I'm not sure why this is the case, since all my integer constants are defined as long int. Any ideas?


    Lastly, on a physical note, I am now inclined to believe that the only guage there can be for true randomness is close adherence to the theortical probabilities of known events. So a randomness source is close to being 'truly random' if it delivers each element of a binary distribution approximately 50&#37; of the time, spread out over a distribution much greater period. That would encompass both even distribution and unpredictability. This is where probabilistic manifestation starts to feel mystical (what ensures that a coin will flip heads 50% of the time?). Of course its no more mystical than the force of gravity, but theres a certain allure to it which is what drew me to this project.
    Last edited by shawnt; 06-11-2008 at 09:10 AM.

  15. #15
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Completely confusing error. Dev-C++ can be so unhelpful.
    A better error is "cannot convert from void to int," or in other words: srand does not return anything so you can't assign its return to anything.
    And you can drop the "void" in the function header. It's not required in C++.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. random to int?
    By psyadam in forum C# Programming
    Replies: 7
    Last Post: 07-22-2008, 08:09 PM
  2. Lesson #3 - Math
    By oval in forum C# Programming
    Replies: 2
    Last Post: 04-27-2006, 08:16 AM
  3. Another brain block... Random Numbers
    By DanFraser in forum C# Programming
    Replies: 2
    Last Post: 01-23-2005, 05:51 PM
  4. How do I restart a random number sequence.
    By jeffski in forum C Programming
    Replies: 6
    Last Post: 05-29-2003, 02:40 PM
  5. Best way to generate a random double?
    By The V. in forum C Programming
    Replies: 3
    Last Post: 10-16-2001, 04:11 PM