【问题标题】:Random number generator in java with long seed valuesjava中具有长种子值的随机数生成器
【发布时间】:2016-05-11 11:46:54
【问题描述】:

超级菜鸟问题(来自一个不懂按位的人):

我在 JavaScript 中使用下面的伪随机数生成器(在我的服务器上)。

Math.seed = function(s) {
    var m_w  = s;
    var m_z  = 987654321;
    var mask = 0xffffffff;

    return function() {
      m_z = (36969 * (m_z & 65535) + (m_z >> 16)) & mask;
      m_w = (18000 * (m_w & 65535) + (m_w >> 16)) & mask;

      var result = ((m_z << 16) + m_w) & mask;
      result /= 4294967296;

      return result + 0.5;
    }
}

var myRandomFunction = Math.seed(1234);
var randomNumber = myRandomFunction();

现在我想在 Java 中使用它(在我的客户端上)。这适用于 int 种子值(例如 1234 的种子在 JS 和 Java 上给出相同的数字),但我的种子值很长。如何更改按位运算符?

public class CodeGenerator {
    private int m_w;
    private int mask;
    private int m_z;

    public CodeGenerator(int seed) {
        m_w = seed;
        m_z = 987654321;
        mask = 0xffffffff;
    }

    public int nextCode() {
        m_z = (36969 * (m_z & 65535) + (m_z >> 16)) & mask;
        m_w = (18000 * (m_w & 65535) + (m_w >> 16)) & mask;
        int result = ((m_z << 16) + m_w) & mask;
        double result2 = result / 4294967296.0;
        return (int)Math.floor((result2 + 0.5) * 999999);
    }
}

【问题讨论】:

  • 出于好奇...你为什么不使用docs.oracle.com/javase/7/docs/api/java/util/Random.html
  • 用long声明变量和方法。
  • @fhofmann 这会生成不同的数字。对于同一个种子,我需要它们。
  • @Niels JS 部分已在服务器上修复。我必须在客户端上使用它才能获得相同的数字。

标签: javascript java random


【解决方案1】:

在 Java 中,您需要将种子屏蔽为 unsigned int,然后它会产生与 JS 版本相同的数字。

新构造函数:

public CodeGenerator(long seed) {
    mask = 0xffffffff;
    m_w = (int) (seed & mask);
    m_z = 987654321;
}

【讨论】:

    【解决方案2】:

    您是否尝试过只声明种子和第一个结果?

    public class CodeGenerator {
        private long m_w;
        private int mask;
        private int m_z;
    
        public static void main(String... a){
            System.out.println(new CodeGenerator(1234).nextCode()); //result = 237455
            System.out.println(new CodeGenerator(1234567891234L).nextCode()); //result = 246468
        }
    
        public CodeGenerator(long seed) {
            m_w = seed;
            m_z = 987654321;
            mask = 0xffffffff;
        }
    
        public int nextCode() {
            m_z = (36969 * (m_z & 65535) + (m_z >> 16)) & mask;
            m_w = (18000 * (m_w & 65535) + (m_w >> 16)) & mask;
            long result = ((m_z << 16) + m_w) & mask;
            double result2 = result / 4294967296.0;
            return (int)Math.floor((result2 + 0.5) * 999999);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-23
      • 1970-01-01
      • 2013-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多