Thread: Random number generation

  1. #1
    Unregistered
    Guest

    Random number generation

    I am making a random number generator that will either make a 0 or a 1. To do this, I simply used the code:

    random = rand()%2; // generate a 0 or a 1



    How can I make this generate a 1 or 0 with a 50% probability?

    Any hints? Thanks

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You just did. There is a 50% chance that the number generated will be even or odd.

    Code:
    #include <stdio.h>
    #include <time.h>
    int main ( void )
    {
    	int x=0,y=0,z=0;
    	double d=0.0;
    	srand(time(0));
    	for( x = 0; x < 10000000; x++ ) if(rand()%2) y++; else z++;
    	printf("y = %d, z = %d, y %% == %f, z %% = %f",
    		y, z, (float)y/x, (float)z/x );
    	return 0;
    }
    It doesn't get much more balanced than that.

    Quzah.
    Last edited by quzah; 04-16-2002 at 06:52 PM.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. xor linked list
    By adramalech in forum C Programming
    Replies: 23
    Last Post: 10-14-2008, 10:13 AM
  2. Counting number from a random file
    By kamisama in forum C Programming
    Replies: 42
    Last Post: 02-22-2005, 05:16 PM
  3. non repeating random number generation?
    By gencor45 in forum C# Programming
    Replies: 1
    Last Post: 02-08-2005, 05:23 PM
  4. random number between negative and positive number
    By anomaly in forum C++ Programming
    Replies: 6
    Last Post: 12-06-2003, 08:40 AM
  5. Random Number Generation
    By drdroid in forum A Brief History of Cprogramming.com
    Replies: 21
    Last Post: 08-02-2003, 03:35 AM