Skip to content

Instantly share code, notes, and snippets.

@badcc
Created August 23, 2015 17:22
Show Gist options
  • Save badcc/dd3ad345fe2e690c3ac8 to your computer and use it in GitHub Desktop.
Save badcc/dd3ad345fe2e690c3ac8 to your computer and use it in GitHub Desktop.
// Derived from
// http://burtleburtle.net/bob/rand/smallprng.html
// TODO(alex): SSE intrinsic
#if !defined(AB_RAND_H)
#define AB_RAND_H
#define ULONG_MAXF 4294967295.0 // 2^32-1
// Internal affixation, _
// 32 bit (u4, ulong)
#define _ab_rand_rot(x,k) (((x)<<(k))|((x)>>(32-(k))))
typedef unsigned long int u4;
typedef struct ab_random_series { u4 a; u4 b; u4 c; u4 d; } ab_random_series;
// [0, ULONG_MAXF]
u4 ab_random(ab_random_series *Series) {
u4 e = Series->a - _ab_rand_rot(Series->b, 27);
Series->a = Series->b ^ _ab_rand_rot(Series->b, 17);
Series->b = Series->c + Series->d;
Series->c = Series->d + e;
Series->d = e + Series->a;
return Series->d;
}
// [0, 1]
float ab_random_unilateral(ab_random_series *Series) {
float Result = ab_random(Series) / ULONG_MAXF;
return(Result);
}
// [-1, 1]
float ab_random_bilateral(ab_random_series *Series) {
float Result = ab_random_unilateral(Series) * 2.0 - 1.0;
return(Result);
}
// [Min, Max]
u4 ab_random_between(ab_random_series *Series, u4 Min, u4 Max) {
u4 Result = ab_random(Series) % (Max - Min) + Min;
return Result;
}
void ab_random_seed(ab_random_series *Series, u4 Seed) {
Series->a = 0xf1ea5eed, Series->b = Series->c = Series->d = Seed;
for (int SeedIndex = 0; SeedIndex < 20; ++SeedIndex) {
(void)ab_random(Series);
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment