/* Pseudorandom Generator on 1996/12/ 5 by tutimura(a)nn.iij4u.or.jp http://www.nn.iij4u.or.jp/~tutimura/c/ my_rand() returns a integer number between 0 and MY_RAND_MAX. MY_RAND_MAX == 65535 when using on gcc. my_srand(seed) sets random seed. They are similar to rand(), srand(), RAND_MAX in . The algorithm is based on linear congruential method, almost same as the one which ANSI explain as a sample. But this is not the best way. Use this to get same numbers independent from compilers. To get random numbers [0,N), calculate ( my_rand() % N ), or (int)( (double)my_rand() / (MY_RAND_MAX+1) * N ). Latter is slow but better. Not to get same numbers, do as below. #include main() { my_srand( time(NULL) ); ... } (updated on 2001/5/31) Please consult Mersenne Twister for a better random generator. (http://www.math.keio.ac.jp/~matumoto/mt.html) */ #include #define MY_RAND_MAX ( ULONG_MAX / 65536L ) #if UINT_MAX < MY_RAND_MAX #undef MY_RAND_MAX #define MY_RAND_MAX UINT_MAX #endif static unsigned long my_rand_seed = 1; /* set seed */ void my_srand( unsigned long seed ) { my_rand_seed = seed; } /* generator */ unsigned my_rand( void ) { my_rand_seed *= 1103515245UL; my_rand_seed += 12345; return (unsigned)( my_rand_seed / 65536L ); } #ifdef TEST #include #include void main() { int i; printf( "MY_RAND_MAX = %u\t", MY_RAND_MAX ); printf( " RAND_MAX = %u\n", RAND_MAX ); for ( i=0; i<10; i++ ) { printf( "%6X - %6X\n", my_rand(), rand() ); } } #endif