简体   繁体   English

有没有简单的方法可以将遇到溢出的整数函数求逆?

[英]Is there a simple way to invert an integer function that experiences overflow?

I'm trying to create an inverse function for the java.util.Random setSeed and next functions. 我正在尝试为java.util.Random setSeed和next函数创建一个逆函数。 Essentially I want to be able to input a long value (before it's truncated to 48 bits) and get back a seed or family of seeds that will result in that value for the first nextLong() call. 本质上,我希望能够输入一个长值(在将其截断为48位之前)并获取一个种子或一族种子,这些种子或种子家族将在第一次调用nextLong()时产生该值。 Its relevant source code is below: 其相关的源代码如下:

setSeed(long seed) setSeed(长种子)

seed = (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1)

next(int bits) 下一个(整数位)

//this function is called by nextLong()
seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)

The problem seems to occur because of the second part, as the integer overflows after the multiplication. 该问题似乎是由于第二部分而发生的,因为整数在乘法之后会溢出。 Because of this, I can't simply divide out the constant as it will end up with a different result and will NOT give me the correct seed. 因此,我不能简单地将常数除,因为它最终会得到不同的结果,并且不会给我正确的种子。

I'm not very experienced in binary operations and was wondering if there's a way to account for this overflow when dividing to obtain the correct seed without having to guess what the really big post-multiplication number actually was. 我对二进制运算的经验不是很丰富,并且想知道在进行除法以获得正确的种子时是否有一种方法可以解决此溢出问题,而不必猜测实际的大乘法数是多少。

Wondering if what you really want is a random number generator, where the first number generated is a specific value. 想知道您真正想要的是一个随机数生成器,其中生成的第一个数字是一个特定值。

class MyRandom extends java.util.Random {
    long targetValue;
    long offset;
    int count=0;

    public MyRandom(long target) {
        this.targetValue = target;
   } 

   public long nextLong() {
        long rnd = super.nextLong();
        if(count++==0) {
            offset = target - rnd;
        }
        return rnd + offset;
   }
}

On the first call to nextLong it will set the offset and return target. 第一次调用nextLong时,它将设置偏移量并返回目标。 On all calls it will return the random number shifted by a fixed amount. 在所有通话中,它将返回随机数字,并偏移固定数量。 This should give a uniform distribution. 这应该给出均匀的分布。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM