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 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.1 comment
a_tartarugaabout 3 hours ago
This is brilliant thanks!
Read the full thread on Hacker News →
Related stories
- Hacker News · 3 points · 2 months ago
- Launch HN: Vespper (YC F24) – SOTA Docx MCPvespper.comHacker News · 31 points · 2 months ago
- Show HN: NetWasm – Independent .NET Compiler/Runtime (82.5 KB Hello World in C#)playground.netwasm.comHacker News · 5 points · 2 months ago
- Hacker News · 47 points · about 2 months ago
- Hacker News · 1 points · 2 months ago
- Hacker News · 15 points · 2 months ago