首页 > 解决方案 > 如何构建伪数生成器以在 JS 和 C# 中具有相同的结果

问题描述

在我构建了一个从初始种子生成伪数的 JS 函数之后,我在 C# 中创建了相同的函数,期望得到相同的结果。经过 6 次迭代后,结果有所不同......有人可以帮助我构建这样一个在 JS 和 C# 中生成相同值的函数吗?

using System;

public class PSR
{
    public int ITN { get; private set; } = 0;
    public int IntITN { get; private set; } = 0;

    private double seed;

    public PSR(double seed)
    {
        this.seed = seed + 0.5;  // avoid 0
    }

    public double Next()
    {
        ITN++;
        var x = Math.Sin(this.seed) * 1000;
        var result = x - Math.Floor(x);  // [0.0,1.0)
        this.seed = result;  // for next call
        return result;
    }

    public double NextInt(double lo, double hi)
    {
        IntITN++;
        var x = this.Next();
        return Math.Truncate((hi - lo) * x + lo);
    }

}

TS版

export class Psr
{
  itn: number = 0;
  intItn:number = 0;
  constructor(private seed) {
    this.seed = seed + 0.5;  // avoid 0
  }

  next() {
    this.itn++
    let x = Math.sin(this.seed) * 1000;
    let result = x - Math.floor(x);  // [0.0,1.0)
    this.seed = result;  // for next call
    return result;
  }

  nextInt(lo, hi) {
    this.intItn++
    let x = this.next();
    return Math.trunc((hi - lo) * x + lo);
  }
}

标签: javascriptc#random-seedgenerate

解决方案


我没有使用 C# 进行测试的环境,但是像简单的LCG这样的东西应该可以在两者中使用。

在 JavaScript 中,您可能有如下实现:

const random  = (seed = 3) => () => (seed = (seed * 1103515245 + 12345) % 0xffffffff) / 0xfffffff

const prng = random(); // 3 as default seed

for (let i = 0; i < 100; i ++)
  console.log(prng());

这不应该给任何要实现的语言带来太多问题。


推荐阅读