7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Haxeで疑似乱数生成

Last updated at Posted at 2014-05-26

Haxeで疑似乱数を生成するためのコードです。
標準ライブラリにMath.random()などがありますが、シード値を使えないので自分で作ってみました。
Xorshiftアルゴリズムを利用しています。
x,y,z,wはシード値です。UIntの正の整数か0を入力してください。
ただし、x + y + z + w = 0だと動かないので注意!

class Xorshift {

	private var x:UInt;
	private var y:UInt;
	private var z:UInt;
	private var w:UInt;
	
	private var t:UInt;
	
	public function new(x:UInt = 1234, y:UInt = 5678, z:UInt = 9876, w:UInt = 5432) {
		this.x = x;
		this.y = y;
		this.z = z;
		this.w = w;
	}
	
	public function nextUInt():UInt {
		t = x ^ (x << 11);
		x = y;
		y = z;
		z = w;
		return w = (w ^ (w >>> 19)) ^ (t ^ (t >>> 8)); 
	}
	
	public function nextFloat():Float {
		t = x ^ (x << 11);
		x = y;
		y = z;
		z = w;
		w = (w ^ (w >>> 19)) ^ (t ^ (t >>> 8));
		return w / 4294967295;
	}
	
}

nextUInt関数は0以上4294967295以下のUInt値、nextFloatは0以上1以下のFloat値を返します。

参考:
http://ja.wikipedia.org/wiki/Xorshift
http://d.hatena.ne.jp/pashango_p/20090717/1247848900

7
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?