Reputation: 8319
In Python, if I use this code:
import random
random.seed(123)
print(random.random())
The first random number will always be 0.052363598850944326
, since I'm giving it the same seed every time I run the program.
JavaScript doesn't have a built-in way to use seeds. I've tried out a JavaScript script called mersenne-twister.js, since that's the type of PRNG that Python uses. But even if I use the same seed, I get a different result than I do in Python.
var m = new MersenneTwister(123);
m.genrand_int32();
That code will always return 0.6964691872708499
the first time that it's run.
How can I use a given seed to get the same random number in both Python and JavaScript?
Upvotes: 2
Views: 3397
Reputation: 920
If you don't need a cryptographically secure pseudorandom number generator, you could use something like this, using the decimals of sinus function.
In python:
import math
def simple_random(precision=10000):
i = 1
while 1:
x = math.sin(i) * precision
yield x - math.floor(x)
i += 1
In Javascript:
var i = 1;
function simple_random(precision=10000) {
x = Math.sin(i++) * precision;
return x - Math.floor(x);
}
If you want to vary seeds, you could use something like sin(a * i + b) rather than sin(i) or a * sin(i + b), it's up to you to find something good enough.
Upvotes: 0
Reputation: 3662
This library/plugin worked for me when I compared the Python output to the JavaScript output.
https://github.com/davidbau/seedrandom
Upvotes: 1