Advertisement
Guest User

Untitled

a guest
Mar 2nd, 2013
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.76 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdint.h>
  4. #include <inttypes.h>
  5. #include <time.h>
  6.  
  7. #define unlikely(x)  __builtin_expect (!!(x), 0)
  8.  
  9. uint32_t state[2] = { 0, 0 };
  10.  
  11. static const double dummy = (double)(1 << 20);
  12.  
  13. inline double my_rand(){
  14.  uint32_t temp;
  15.  uint64_t temp64;
  16.  double *temp64_d = (double *) &temp64;
  17.  uint64_t two_20 = * ( uint64_t * ) &dummy;
  18.  
  19.  if ( unlikely ( state[0] == 0 ) ) {
  20.   state[0] = random();
  21.   state[1] = random();
  22.  }
  23.  
  24.   // Mix the bits.  Never replaces state[i] with 0 if it is nonzero.
  25.   state[0] = 18273 * (state[0] & 0xFFFF) + (state[0] >> 16);
  26.   state[1] = 36969 * (state[1] & 0xFFFF) + (state[1] >> 16);
  27.  
  28.   temp = (state[0] << 14) + (state[1] & 0x3FFFF);
  29.  
  30.   temp64 = temp;
  31.   temp64 ^= two_20;
  32.   return *temp64_d - dummy;
  33. }
  34.  
  35. int trial() {
  36.     int count = 0;
  37.     double sum = 0;
  38.     while (sum <= 1.0) {
  39.         sum += rand() / (double) RAND_MAX;
  40.         count++;
  41.     }
  42.     return count;
  43. }
  44.  
  45. int trial2() {
  46.     int count = 0;
  47.     double sum = 0;
  48.     while (sum <= 1.0) {
  49.         sum += my_rand();
  50.         count++;
  51.     }
  52.     return count;
  53. }
  54.  
  55. double monteCarlo(int trial_type, int n) {
  56.     int i, total = 0;
  57.     if ( trial_type == 1 ) { // Use rand()
  58.       printf("Using original rand() implementation.\n");
  59.       for (i = 0; i < n; i++) {
  60.           total += trial();
  61.       }
  62.     } else { // Use my_rand()
  63.       printf("Using V8-style rand function.\n");
  64.       for (i = 0; i < n; i++) {
  65.           total += trial2();
  66.       }
  67.     }
  68.     return total / (double) n;
  69. }
  70.  
  71. int main(int argc, char *argv[]) {
  72.     int i = 0;
  73.     srandom(time(NULL));
  74.     if ( argv[1][0] == '1' )
  75.       printf("%f\n", monteCarlo(1,100000000));
  76.     else
  77.       printf("%f\n", monteCarlo(2,100000000));
  78.     return 0;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement