Advertisement
palmerstone

Mersenne Twister

Mar 16th, 2013
433
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.11 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. unsigned int cur = 0, twister[624] = {0};
  6.  
  7. void generate_seed(){
  8.     int i;
  9.     for (i = 0; i < 624; i++){
  10.         unsigned int x = (twister[i] & 0x80000000) + (twister[(i + 1) % 624] & 0x7fffffff);
  11.         twister[i] = twister[(i + 397) % 624] ^ (x >> 1);
  12.         if (!(x & 1)) twister[i] = (twister[i] ^ 0x9908b0df);
  13.     }
  14. }
  15.  
  16. int random(){
  17.     if (cur == 0) generate_seed();
  18.  
  19.     unsigned int res = twister[cur];
  20.     cur++;
  21.     if (cur == 624) cur = 0;
  22.  
  23.     res = res ^ (res >> 11U);
  24.     res = res ^ ((res << 7U) & 0x9d2c5680);
  25.     res = res ^ ((res << 15U) & 0xefc60000);
  26.     res = res ^ (res >> 18U);
  27.  
  28.     return res;
  29. }
  30.  
  31. int main(){
  32.     int i, j;
  33.     srand(time(0));
  34.     twister[0] = rand();
  35.  
  36.     for (i = 1; i < 624; i++){
  37.         twister[i] = (1812433253U * twister[i - 1]) ^ (twister[i - 1] >> 30U);
  38.     }
  39.  
  40.     int lim = 1000000;
  41.     int even = 0, odd = 0;
  42.     for (i = 0; i < lim; i++){
  43.         int r = random();
  44.         if (r & 1) odd++;
  45.         else even++;
  46.     }
  47.  
  48.     printf("%d %d\n", even, odd);
  49.  
  50.     return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement