xorshift-struct.c (885B)
1 #include <stdint.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 5 struct xorshift32_state { 6 uint32_t a; 7 }; 8 9 uint32_t xorshift32(struct xorshift32_state *state) 10 { 11 /* Algorithm "xor" from p. 4 of Marsaglia, "Xorshift RNGs" */ 12 uint32_t x = state->a; 13 x ^= x << 13; 14 x ^= x >> 17; 15 x ^= x << 5; 16 return state->a = x; 17 } 18 19 float rand_xorshift32(struct xorshift32_state *state){ 20 return (float) xorshift32(state) / (float) UINT32_MAX; 21 } 22 23 24 int main(){ 25 struct xorshift32_state** states = malloc(sizeof(struct xorshift32_state*) * 4); 26 for(int i=0; i<4;i++){ 27 states[i] = malloc(sizeof(struct xorshift32_state)); 28 states[i]->a = (uint32_t) i + 1; 29 } 30 31 for(int i=0; i<1000000000; i++){ 32 uint32_t x = xorshift32(states[0]); 33 float y = rand_xorshift32(states[1]); 34 // printf("%u\n", x); 35 // printf("%f\n", y); 36 } 37 38 for(int i=0; i<4;i++){ 39 free(states[i]); 40 } 41 free(states); 42 43 44 return 0; 45 } 46