【问题标题】:Seeded random that has floats as input and output for possible recursion具有浮点数作为可能递归的输入和输出的种子随机数
【发布时间】:2019-09-16 09:23:32
【问题描述】:

我正在寻找能够重现结果的种子解决方案。 对于我的方法的每次递归运行,我需要一个介于 0 和 1 之间的随机浮点数,因此我需要使用以前的种子或浮点数来生成新的随机浮点数或种子。 所以我需要一个种子生成器或种子是浮动的种子浮动生成器。 有什么想法吗?

【问题讨论】:

  • 希望对您有所帮助stackoverflow.com/questions/686353/…
  • 它似乎专注于从伪随机中随机生成,这不是我想要做的,无论如何谢谢:)
  • 您能解释一下您正在制作的应用程序需要您描述的生成器吗?
  • 我正在尝试可视化一棵树,并且每个分支都需要有轻微的不规则性,并且我需要能够用种子重新创建完全相同的树

标签: javascript recursion random seed random-seed


【解决方案1】:

试试

// 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()) );

【讨论】:

    【解决方案2】:

    您要求的只是种子 PRNG。

    您只需对种子进行硬编码,然后按顺序调用它。

    // 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
    */

    如果您希望让它在第 n 次迭代时返回值,那么只需创建一个具有相同种子的新实例并在获取之前调用它 n 次价值。

    // 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 ) );

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-28
      • 1970-01-01
      • 1970-01-01
      • 2014-11-10
      • 2014-12-03
      • 1970-01-01
      • 2012-09-27
      • 1970-01-01
      相关资源
      最近更新 更多