45 lines
1.3 KiB
C
45 lines
1.3 KiB
C
// gcc nomod.c -o nomod; ./nomod
|
|
|
|
/*
|
|
Explanation:
|
|
|
|
* rand is treated as a 32-bit fixed-point number in [0, 1) (implicitly scaled by 2³²).
|
|
* Multiplying by len scales it to [0, len).
|
|
* Shifting right by 32 bits extracts the integer part (0..len-1).
|
|
|
|
I guess I will go with decimal system for understanding this...
|
|
So lets say I have two-digit decimal numbers from 00..99 this
|
|
means that multiplying two of these should always fit in a
|
|
four-digit decimal number isn't it? from 0000..9999 because
|
|
99*99 is 9801 so it fits in and its the biggest possible pairs
|
|
to multiply.
|
|
|
|
Now lets have a "len" number with also at most two digits, let
|
|
it be 20 - this will be our "modulus". Lets multiply a random
|
|
two-digit number with this. We get lets say 71*20 which is 1400.
|
|
Shifting two digits to the right it becomes 14. If I do 99*20
|
|
(which is biggest) I get 1980 so when shiften decimally it
|
|
becomes 19 (which is again smaller than 20).
|
|
|
|
It looks like the random numbers from 00..99 indeed start to map
|
|
onto 00..19 in this case. Very fascinating! Just avoid cryptin'
|
|
*/
|
|
|
|
#include <stdio.h>
|
|
#include <stdint.h>
|
|
#include "fastrand.h"
|
|
|
|
int main() {
|
|
uint32_t from = 12;
|
|
uint32_t to = 32;
|
|
int n = 30;
|
|
|
|
rand_state rs = init_rand();
|
|
for(int i = 0; i < n; ++i) {
|
|
uint32_t choice = rand_between(&rs, from, to);
|
|
printf("rand [%u, %u): %u\n", from, to, choice);
|
|
}
|
|
|
|
return 0;
|
|
}
|