time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

xorshift-pointer.c (879B)


      1 #include <stdint.h>
      2 #include <stdio.h>
      3 #include <stdlib.h>
      4 
      5 uint32_t xorshift32(uint32_t* state)
      6 {
      7 	/* Algorithm "xor" from p. 4 of Marsaglia, "Xorshift RNGs" */
      8 	uint32_t x = *state;
      9 	x ^= x << 13;
     10 	x ^= x >> 17;
     11 	x ^= x << 5;
     12 	return *state = x;
     13 }
     14 
     15 float rand_xorshift32(uint32_t* state){
     16 	return (float) xorshift32(state) / (float) UINT32_MAX;
     17 }
     18 
     19 int main(){
     20 	uint32_t** states = malloc(4 * sizeof(uint32_t*));
     21 	for(int i=0; i<4;i++){
     22 		states[i] = malloc(sizeof(uint32_t));
     23 		*states[i] = (uint32_t) i + 1;
     24 	}
     25 	for(int i=0; i<1000000000;i++){
     26 		uint32_t x = xorshift32(states[0]);
     27 		float y = rand_xorshift32(states[1]);
     28 		// printf("%u\n", x);
     29 	  // printf("%f\n", y);
     30 	}
     31   
     32 	for(int i=0; i<4;i++){
     33 		free(states[i]);
     34 	}
     35 	free(states);
     36 
     37   return 0;
     38 }
     39 
     40 // See <https://stackoverflow.com/questions/53886131/how-does-xorshift32-works>
     41 // https://en.wikipedia.org/wiki/Xorshift