Adjusting XORShift generator to return a number within a maximum

后端 未结 2 1171
天涯浪人
天涯浪人 2021-01-02 04:43

I need to generate random integers within a maximum. Since performance is critical, I decided to use a XORShift generator instead of Java\'s Random class.

2条回答
  •  既然无缘
    2021-01-02 05:45

    I had some fun with your code and came up with this:

    public class XORShiftRandom {
    
    private long last;
    private long inc;
    
    public XORShiftRandom() {
        this(System.currentTimeMillis());
    }
    
    public XORShiftRandom(long seed) {
        this.last = seed | 1;
        inc = seed;
    }
    
    public int nextInt(int max) {
        last ^= (last << 21);
        last ^= (last >>> 35);
        last ^= (last << 4);
        inc += 123456789123456789L;
        int out = (int) ((last+inc) % max);     
        return (out < 0) ? -out : out;
    }
    
    }
    

    I did a simple test and it is about Four times as fast as the java.util.Random

    If you are intrested in how it works you can read this paper:

    Disclamer:

    The code above is designed to be used for research only, and not as a replacement to the stock Random or SecureRandom.

提交回复
热议问题