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.

scravy
  • 11,904
  • 14
  • 72
  • 127

1 Answers1

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

Tom van der Woerdt
  • 29,532
  • 7
  • 72
  • 105
  • @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 Dec 01 '13 at 11:11
  • 2
    @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` – Tom van der Woerdt Dec 01 '13 at 14:41
  • 1
    The name of this algorithm is "Mersenne Twister". More information here: https://en.wikipedia.org/wiki/Mersenne_twister – Blaise May 11 '14 at 12:15