I would like to implement an XorShift PRNG in both Java, Python and Javascript. The different implementations must generate the exact same sequences given the same seed. So far, I've have not been able to do this.
My implementation in Java
have the following implementation of an XorShift PRNG in Java (where x is a long field):
public long randomLong() {
x ^= (x << 21);
x ^= (x >>> 35);
x ^= (x << 4);
return x;
}
If I seed x to 1, the first four calls to randomLong() will generate:
35651601
1130297953386881
-9204155794254196429
144132848981442561
My implementation in Python
I have tried both with and without numpy. Below is the version that uses numpy.
def randomLong(self):
self.x ^= np.left_shift(self.x, 21)
self.x ^= np.right_shift(self.x, 35)
self.x ^= np.left_shift(self.x, 4)
return self.x
With the same seed, the Python function will generate:
35651601
1130297953386881
-9204155787274874573 # different
143006948545953793 # different
My Javascript implementation
I've not attempted one yet, since Javascripts only number type seems to be doubles based on IEEE 754, which opens up a different can of worms.
What I think the cause is
Java and Python have different number types. Java has 32 and 64-bit integers, while Python has funky big int types.
It seems that the shift operators have different semantics. For example, in Java there is both logical and arithmetic shift, while in Python there is only one type of shift (logical?).
Questions
I would be happy with an answer that lets me write a PRNG in these three languages, and one that is fast. It does not have to be very good. I have considered porting C libs implementations to the other languages, although it is not very good.
- Can I fix my above implementations so they work?
- Should I switch to another PRNG function that is easier to implement across prog.langs?
I have read the SO where someone suggested using the java-random package for Python. I don't want this, I'm also going to need the function in Javascript, and I don't know that this packages exists there.
Aucun commentaire:
Enregistrer un commentaire