Skip to content

Instantly share code, notes, and snippets.

@zoon
Created March 11, 2011 02:03
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 zoon/865342 to your computer and use it in GitHub Desktop.
Save zoon/865342 to your computer and use it in GitHub Desktop.
package;
/**
* Xorshift preudorandom number generator for Haxe.
* Reference: http://en.wikipedia.org/wiki/Xorshift
*/
class Xorshift
{
inline public static var INT_MAX:Int = 0x7FFFFFFF; // (2^31 - 1)
inline public static var INT_MAXPLUSONE:Float = 2147483648.0;
private var _seed:Int;
public function new(?seed:Int)
{
if (seed == 0)
throw "Xorshift can't use zero seed";
if (seed == null)
seed = Std.int(1 + Math.random() * (INT_MAX - 1));
_seed = seed;
}
public function reSeed(newSeed:Int):Void
{
if (newSeed == 0)
throw "Xorshift can't use zero seed";
_seed = newSeed;
}
/**
* Returns a random Int in [INT_MIN, 0) U (0, INT_MAX]
*/
inline private function gen32():Int
{
_seed ^= (_seed << 13);
_seed ^= (_seed >>> 17);
return _seed ^= (_seed << 5);
}
/**
* Returns a random Int in [0, INT_MAX]
*/
inline private function gen31():Int
{
return gen32() & INT_MAX;
}
/**
* Returns a random Float in [0, 1), low resolution
*/
public function random():Float
{
return gen31() / INT_MAXPLUSONE;
}
/**
* Return a random Int in [0, n)
*/
public function rand(n:Int):Int
{
if (n <= 0 || n > INT_MAX)
throw "n out of (0, INT_MAX]";
var bucket_size = Std.int(INT_MAX / n);
var r;
do
{
r = Std.int(gen31() / bucket_size);
}
while (r >= n);
return r;
}
/**
* Returns a random Int in [min, max) by dafault,
* or in [min, max] if includeMax == true;
*/
public function randInterval(min:Int, max:Int, ?includeMax:Bool=false)
{
if (min < 0 || max < 1 || max < min)
throw "arguments error";
return min + rand(max - min + (includeMax ? 1 : 0));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment