I am looking for a seeded solution to be able to reproduce results. I need a random float between 0 and 1 for each recursive run of my method, so I need to use the previous seed or float to produce a new random float or seed. So I am in need of a seeded seed generator or a seeded float generator where the seed is a float. Any ideas?
Asked
Active
Viewed 132 times
1
-
I hope this will help you https://stackoverflow.com/questions/686353/random-float-number-generation – Anurag Tomar Sep 16 '19 at 09:26
-
It seems to focus on making a random from a pseudo-random, which is not what I am trying to do, thanks anyway :) – XGG Sep 16 '19 at 09:38
-
Can you explain what application you are making that requires a generator you describe? – Peter O. Sep 16 '19 at 16:30
-
I am trying to visualize a tree and need a slight irregularity at each branch, and I need to be able to recreate the exact same tree with a seed – XGG Sep 17 '19 at 08:58
2 Answers
0
Try
// crypto-strong random num in rage [0,1)
let random = ()=> crypto.getRandomValues(new Uint32Array(1))[0]/2**32;
function recursive(n,rand) {
return n>0 ? recursive(n-1, rand/2) : rand;
}
console.log( recursive(5,random()) );

Kamil Kiełczewski
- 85,173
- 29
- 368
- 345
0
What you are asking for is just a seeded PRNG.
You just have to hard-code the seed and then call it in order.
// rewrite of https://gist.github.com/blixt/f17b47c62508be59987b
class Random {
constructor( seed ) {
this._seed = seed % 0x7fffffff;
if (this._seed <= 0) { this._seed += 0x7ffffffe; }
}
next() {
const next_int = this._seed =
this._seed * 0x41a7 % 0x7fffffff;
return ( next_int - 1 ) / 0x80000000;
}
}
const my_seed = 42; // just hard-code this
const rand = new Random( my_seed );
let i = 0;
while( i++ < 5 ) {
console.log( rand.next() );
}
/*
0.000328707043081522
0.524587101303041
0.735423531383276
0.2633055401965976
0.37622397067025304
*/
If you ever wish to make it return the value at n-th iteration, then just create a new instance with the same seed and call it n times before getting the value.
// rewrite of https://gist.github.com/blixt/f17b47c62508be59987b
class Random {
constructor( seed ) {
this._seed = seed % 0x7fffffff;
if (this._seed <= 0) { this._seed += 0x7ffffffe; }
}
next() {
const next_int = this._seed =
this._seed * 0x41a7 % 0x7fffffff;
return ( next_int - 1 ) / 0x80000000;
}
}
function getRandAtIndex( index = 0, seed ) {
const gen = new Random( seed );
let i = 0;
while( i++ < index ) {
gen.next();
}
return gen.next();
}
// this time we use a random seed
const my_seed = Math.random() * 0xFFFFFFFF;
const rand = new Random( my_seed );
// log the five first values
let i = 0;
while( i++ < 5 ) {
console.log( rand.next() );
}
console.log( '\nthird value was', getRandAtIndex( 2, my_seed ) );

Kaiido
- 123,334
- 13
- 219
- 285