javascript - 如何构建伪数生成器以在 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);
}
}
解决方案
我没有使用 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());
这不应该给任何要实现的语言带来太多问题。
推荐阅读
- python - 结束后如何循环此代码以及如何使代码的 Y/N 部分工作?
- python - Python拼接列表在向后工作时不包含第一个元素
- python - 在 Python 中,与大多数语言一样,您使用 0 访问列表中的第一项。但是从 1 开始会是更好的选择吗?
- python - 使用按钮选择中断 For 循环
- r - 如何在 R 中插入数据框的每一行?
- python - Discord Python Bot:升级系统
- winforms - Finding window in VS2017 using information from Spy++
- java - Oracle 11g 数据库中具有不同会话的相同 SQL_ID
- google-apps-script - 使用 WorkBook 中另一个电子表格中的 =UNIQUE - Google Apps 脚本
- mysql - 如何在 macOS 上的 MariaDB 10.4 中设置 root 密码?