MULE 0.0.1
Multi-Use Library Essentials
Loading...
Searching...
No Matches
rand.c
1#include "rand/rand.h"
2
3#include <assert.h>
4
5uint64_t rand_next(Rand *r) {
6 uint64_t z = (r->state += 0x9E3779B97F4A7C15u);
7 z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9u;
8 z = (z ^ (z >> 27)) * 0x94D049BB133111EBu;
9 return z ^ (z >> 31);
10}
11
12uint64_t rand_below(Rand *r, uint64_t n) {
13 assert(n != 0);
14 /* Reject the low values that would make some results more likely. */
15 uint64_t threshold = -n % n;
16 for (;;) {
17 uint64_t x = rand_next(r);
18 if (x >= threshold) return x % n;
19 }
20}
uint64_t state
The seed, advanced by every call.
Definition rand.h:27
uint64_t rand_below(Rand *r, uint64_t n)
A uniform value in [0, n).
Definition rand.c:12
uint64_t rand_next(Rand *r)
The next 64 random bits.
Definition rand.c:5
Generator state.
Definition rand.h:26