time-to-botec/C/xorshift-scratchpad/xorshift-pointer.c

42 lines
879 B
C
Raw Normal View History

2023-06-03 09:38:40 +00:00
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
uint32_t xorshift32(uint32_t* state)
2023-06-03 09:38:40 +00:00
{
/* Algorithm "xor" from p. 4 of Marsaglia, "Xorshift RNGs" */
uint32_t x = *state;
2023-06-03 09:38:40 +00:00
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
return *state = x;
2023-06-03 09:38:40 +00:00
}
float rand_xorshift32(uint32_t* state){
2023-06-03 16:02:01 +00:00
return (float) xorshift32(state) / (float) UINT32_MAX;
}
2023-06-03 09:38:40 +00:00
int main(){
uint32_t** states = malloc(4 * sizeof(uint32_t*));
2023-06-03 09:38:40 +00:00
for(int i=0; i<4;i++){
states[i] = malloc(sizeof(uint32_t));
*states[i] = (uint32_t) i + 1;
2023-06-03 09:38:40 +00:00
}
for(int i=0; i<1000000000;i++){
uint32_t x = xorshift32(states[0]);
float y = rand_xorshift32(states[1]);
// printf("%u\n", x);
// printf("%f\n", y);
}
2023-06-03 09:38:40 +00:00
for(int i=0; i<4;i++){
free(states[i]);
2023-06-03 09:38:40 +00:00
}
free(states);
2023-06-03 09:38:40 +00:00
return 0;
}
// See <https://stackoverflow.com/questions/53886131/how-does-xorshift32-works>
// https://en.wikipedia.org/wiki/Xorshift