ckknight / random-js

A mathematically correct random number generator library for JavaScript.
MIT License
605 stars 49 forks source link

Question: Use It In Games? #27

Closed manico closed 5 years ago

manico commented 6 years ago

Hello,

Is it safe to use mt19937 engine (with autoSeed) for RNG games like Roulette? Are the results predictable? If somebody is collecting results, can they predict next drawn number based on previous collected results?

Thank you. :)

ckknight commented 6 years ago

Yeah, one of the reasons I wrote random-js was to have determinism and predictability in order to replay random events such as you describe.

Regarding predicting the next number, I'd consult https://en.wikipedia.org/wiki/Mersenne_Twister - Given that the period is 2 19937, predictability is much harder than with a more typical algorithm which tend to have a periodicity of 2 32.

manico commented 6 years ago

Thanks. So if i understood correctly, next number would be predictable after 2 ** 19937 rounds (let's say I generate random number each round), and that number would be first generated on the beginning of "cycle"?

But there is no way to predict number in "normal" situation? Example of my code:

const Random = require('random-js');

class RngService {
  constructor() {
    const randomEngine = Random.engines.mt19937().autoSeed();
    this.rngGenerator = new Random(randomEngine);
  }

  generate(min, max) {
    return this.rngGenerator.integer(min, max);
  }
}

module.exports = new RngService();

min value is 0 and max value is 36.

I call generate method every 140 seconds. Would someone be able to predict next number before 2 ** 19937 is reached?

Or can someone predict if he knows seed (but I'm using autoSeed)?

ckknight commented 6 years ago

If you know the seed, you can predict the next value easily. The Mersenne Twister is not cryptographically secure.

manico commented 6 years ago

Ok, but no way when seed is unknown, that is fine. autoSeed uses current time and something else so no way to find out that too because it is generated on application start and unknown to end-user (or even developer).

What would you recommend for this case if not mt? Maybe nativeMath or browserCrypto? Would that be supported in node? Or I'm I fine with mt?

ckknight commented 5 years ago

I suggest sticking with the Mersenne Twister. I suggest reading https://en.wikipedia.org/wiki/Mersenne_Twister and possibly some mathematical whitepapers on predicting future random numbers within a twister, but part of its whole purpose is to make such prediction difficult.