💾 Archived View for thrig.me › blog › 2024 › 02 › 05 › jsf.c captured on 2024-06-16 at 13:27:10.
⬅️ Previous capture (2024-03-21)
-=-=-=-=-=-=-
/* Jenkins Small Fast -- "A small noncryptographic PRNG" * http://burtleburtle.net/bob/rand/smallprng.html * https://www.pcg-random.org/posts/some-prng-implementations.html */ #include <stdint.h> #include "jsf.h" #define rot32(x, k) (((x) << (k)) | ((x) >> (32 - (k)))) struct ranctx { uint32_t a; uint32_t b; uint32_t c; uint32_t d; }; static struct ranctx ctx; static uint32_t ranval(void); uint32_t jsf_below(uint32_t upper_bound) { return ((uint64_t) ranval() * (uint64_t) upper_bound) >> 32; } int jsf_coinflip(void) { return ranval() & 1; } void jsf_init(uint32_t seed) { uint32_t i; ctx.a = 0xf1ea5eed, ctx.b = ctx.c = ctx.d = seed; for (i = 0; i < 20; ++i) ranval(); } inline static uint32_t ranval(void) { uint32_t e = ctx.a - rot32(ctx.b, 27); ctx.a = ctx.b ^ rot32(ctx.c, 17); ctx.b = ctx.c + ctx.d; ctx.c = ctx.d + e; ctx.d = e + ctx.a; return ctx.d; }