Skip to content

Instantly share code, notes, and snippets.

@RicoP

RicoP/main.cpp Secret

Last active June 29, 2016 13:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RicoP/40bbbf4db684c6d4838a7cd51dfeec44 to your computer and use it in GitHub Desktop.
Save RicoP/40bbbf4db684c6d4838a7cd51dfeec44 to your computer and use it in GitHub Desktop.
XorRandShuffle
#include <cstdio>
#include <iostream>
#include "xorrand.h"
int main() {
XorRand seed = 0;
for (int i = 0; i != 64; ++i) {
float f = XorRandShuffleFloat(seed);
printf("X: %x, F: %f\n", seed, f);
}
enum {
INIT = 0
};
seed = INIT;
do {
XorRand oldSeed = seed;
XorRandShuffle(seed);
if (oldSeed == seed) {
printf("BREAK: %x\n", seed);
break;
}
++seed;
} while (seed != INIT);
seed = INIT;
do {
XorRand fseed = seed;
float f = XorRandShuffleFloat(fseed);
if (!(f >= 0.0f && f < 1.0f)) {
printf("BREAK: %x, %x, %f\n", seed, fseed, f);
break;
}
++seed;
} while (seed != INIT);
int stat[128] = {};
seed = INIT;
do {
XorRand old = seed;
XorRandShuffle(old);
++stat[old % 128];
++seed;
} while (seed != INIT);
for (int i = 0; i != 128; ++i) {
printf("stat[%i] == %i\n", i, stat[i]);
}
XorRand test = 0;
seed = INIT;
do {
XorRand old = seed;
XorRandShuffle(old);
test ^= old;
++seed;
} while (seed != INIT);
printf("test = %x \n", test);
}
#include <cstdint>
typedef uint32_t u32;
typedef u32 XorRand;
//https://en.wikipedia.org/wiki/Xorshift#Xorshift.2A
//http://www.jstatsoft.org/article/view/v008i14/xorshift.pdf page 4
void XorRandShuffle(XorRand & xorRand) {
// this magic number helps to prevent collisions.
xorRand ^= 0x926a0348;
xorRand ^= xorRand << 13;
xorRand ^= xorRand >> 17;
xorRand ^= xorRand << 5;
}
float XorRandShuffleFloat(XorRand & xorRand) {
XorRandShuffle(xorRand);
union {
XorRand u_x;
float u_f;
};
// Manipulate the exponent and fraction of the floating point number
// in a way, that we get a number from 1 (inlcusive) and 2 (exclusive).
u_x = (xorRand & 0x7FFFFF) ^ 0x3F800000;
return u_f - 1.0f;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment