
前提
ここに質問の内容を詳しく書いてください。
javascriptで、再現性のある浮動小数点数の乱数を生成するにはどうすればいいのでしょうか?xorShiftで試してみたのですが、どうしても数値が偏ったものになってしまいます。
実現したいこと
軽いらしいのでxorShiftの生成法がいいです。Math.random()のように0から1の間の浮動小数点数を得られるものがいいです。
該当のソースコード
javascript
1 function seed(seed){ 2 this._x = 123456789; 3 this._y = 362436069; 4 this._z = 521288629; 5 this._w = seed; 6 } 7 8 seed.prototype.xorShift = function() { 9 let t; 10 t = this._x ^ (this._x << 11); 11 this._x = this._y; this._y = this._z; this._z = this._w; 12 this._w = Math.abs((this._w ^ (this._w >>> 19)) ^ (t ^ (t >>> 8))); 13 return this._w; 14 }; 15 16 17let rand = new seed(1); 18console.log(rand.xorShift()); 19//638953871 20 21rand = new seed(2); 22console.log(rand.xorShift()); 23//638953870 24 25//偏った結果になる 26 27rand = new seed(88675123); 28for(let i = 0; i < 10; i++){ 29 console.log(rand.xorShift()); 30}//繰り返したときは偏らない 31 32/* 33593279510 34458295579 351794091433 36661847884 37516391490 381924314800 391695021998 40717233955 41137846187 42271094485 43*/ 44

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2023/01/11 18:46