javascript - Implementing XorShift the same in Java and Python -
i implement xorshift prng in both java, python , javascript. different implementations must generate exact same sequences given same seed. far, i've have not been able this.
my implementation in java
have following implementation of xorshift prng in java (where x
long
field):
public long randomlong() { x ^= (x << 21); x ^= (x >>> 35); x ^= (x << 4); return x; }
if seed x
1, first 4 calls randomlong()
generate:
35651601 1130297953386881 -9204155794254196429 144132848981442561
my implementation in python
i have tried both , without numpy. below version 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 same seed, python function generate:
35651601 1130297953386881 -9204155787274874573 # different 143006948545953793 # different
my javascript implementation
i've not attempted 1 yet, since javascript's number type seems doubles based on ieee 754, opens different can of worms.
what think cause is
java , python have different number types. java has 32 , 64-bit integers, while python has funky big int types.
it seems shift operators have different semantics. example, in java there both logical , arithmetic shift, while in python there 1 type of shift (logical?).
questions
i happy answer lets me write prng in these 3 languages, , 1 fast. not have good. have considered porting c libs implementations other languages, although not good.
- can fix above implementations work?
- should switch prng function easier implement across prog.langs?
i have read suggested using java.util.random class python. don't want this, since i'm going need function in javascript, , don't know packages exists there.
i happy answer lets me write prng in these 3 languages, , 1 fast. not have good.
you implement 32-bit linear congruential generator in 3 languages.
python:
seed = 0 in range(10): seed = (seed * 1664525 + 1013904223) & 0xffffffff print(seed)
java:
int seed = 0; (int = 0; < 10; i++) { seed = seed * 1664525 + 1013904223; system.out.println(seed & 0xffffffffl); }
javascript:
var seed = 0; (var = 0; < 10; i++) { // intermediate result fits in 52 bits, no overflow seed = (seed * 1664525 + 1013904223) | 0; console.log(seed >>> 0); }
output:
1013904223 1196435762 3519870697 2868466484 1649599747 2670642822 1476291629 2748932008 2180890343 2498801434
note in 3 languages, each iteration prints unsigned 32-bit integer.
Comments
Post a Comment