If you're doing Monte Carlo try Knuth LGC

1 point by logicallee 12 minutes ago

I was doing a monte carlo simulation involving a few million iterations and that didn't really need anything all that random. I remembered reading about a fast algorithm for very fast values (just a couple of ops), so I asked about this and was surprised that there is one. I just inserted it into my c code and it became ten times faster. If you're doing some monte carlo simulations where you don't need anything very random, give it a try.

before: 3.5 seconds. after: 0.42 seconds.

code I used:

   #include <stdint.h>

   static uint32_t seed = 1;   // any non-zero value is fine

   static inline uint32_t fast_rand(void) {
       seed = seed * 1664525u + 1013904223u;   // mod 2^32 is free
       return seed;
   }

   // then (example):
   int ch = fast_rand() % 1297 // where 1297 is the range.

(there's a slight bias when using % this way.) code gave the same results so it was still correct. you would adjust 1297 to the range you need an integer result in, this is from my example.