8

I'm looking for a random number generator in JavaScript which I can initialize with a certain seed and gives a deterministic result (according to that seed). It should be capable of providing random integers within a certain range, however I can work with a random number generator that spits doubles, too (just like Math.random()).

Basically I'm looking for an equivalent to java.util.Random as known in the Java World for JavaScript.

Is there something like this already built into JavaScript? Is there some (maybe HTML5 related API) which specifies such a thing? Is there a library providing such a random number generator?

I'm implementing a genetic algorithm in JavaScript and I need to be able to harvest the same results for the same inputs (including seed) for research.

4
  • Something like: davidbau.com/archives/2010/01/30/… Commented Nov 30, 2011 at 17:18
  • 2
    @Danny, you can see from his question that he knows about Math - you cannot specify a seed though. Commented Nov 30, 2011 at 17:19
  • 3
    @Danny: Math.random can't be seeded explicitly, and the OP is aware of it. A thorough read of the question should have told you that. ;-) Commented Nov 30, 2011 at 17:19
  • @Prisoner Thanks, I missed that part. Commented Nov 30, 2011 at 17:21

1 Answer 1

12

This might help you, I just found it on the internet. It's apparently a replacement for Math.random()

http://davidbau.com/encode/seedrandom.js

Sign up to request clarification or add additional context in comments.

3 Comments

@Tom What would be the best way to add a range? Perhaps I'm missing something, but David Bau's examples doesn't seem to tell.
@NinjaFart If a RNG has the range [0.0-1.0> then you can just multiply it with the maximum (like 5) and round it down. Because the RNG will never hit 1.0, you get a number from 0 to 4. Similarly, if you want a number between 2 and 10, you'd use Math.random() * 8 + 2
The name of this algorithm is "Mersenne Twister". More information here: en.wikipedia.org/wiki/Mersenne_twister

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.