Tofu
Tofu

Reputation: 3613

Javascript custom prng successive calls produces 0

I'm trying to port the old C standard rand() function over to JavaScript just for testing purposes. I don't plan to use this in a practical scenario so please don't freak out about it being insecure.
This is the C implementation of the function:

seed = seed * 1103515245 + 12345;
return (seed/65536) % 32768;

Where 32768 was RAND_MAX. So I tried porting that over to Javascript:

Random = function(p) {
  this.s = p;
  this.rand = function() {
    this.s = this.s * 1103515245 + 12345;
    return Math.floor((this.s / 65536) % 32768);
  };
};

let r = new Random(Math.floor(new Date() / 1000));
console.log(r.rand()); // gives expected results
console.log(r.rand()); // second call produces 0

When I call r.rand() the first time, it produces the expected result. But then every successive call to r.rand()just gives me 0 and I'm curious as to why…

Upvotes: 3

Views: 102

Answers (1)

Tofu
Tofu

Reputation: 3613

The issue was that this line this.s = this.s * 1103515245 + 12345; was dramatically increasing the value of this.s so by adding a modulus of 232 – 1 the number is restrained to produce the expected results as they would in C.

rand() {
  this.seed = (this.seed*1103515245 + 12345) % 4294967295;
  return (this.seed / 65536) % 32768;
}

It's probably not the best solution but it did seem to solve it.
A modulus Number.MAX_SAFE_INTEGER would work as well in this case, however since the goal was to keep it synced with C, 232 – 1 works okay.

Upvotes: 4

Related Questions