Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "(seed * 9301 + 49297) % 233280 / 233280.0" generate a random number?

Tags:

random

// Found this seed-based random generator somewhere
// Based on The Central Randomizer 1.3 (C) 1997 by Paul Houle ([email protected])

var seed = 1;

/**
 * return a random number based on a seed
 * @param seed
 * @returns {number}
 */
function getNextValue() {
    seed = (seed * 9301 + 49297) % 233280;
    return seed/(233280.0);
}

function setSeed(_seed_) {
    seed = _seed_;
}

module.exports = {
    nextValue: getNextValue,
    seed: setSeed
};

See https://github.com/dylang/shortid/blob/master/lib/random/random-from-seed.js

like image 711
Frank Fang Avatar asked Nov 15 '15 06:11

Frank Fang


2 Answers

Why does (seed * 9301 + 49297) % 233280 / 233280.0 generate a random number?

It doesn't. It generates a completely deterministic number. The resulting sequence may look random at first glance, hence this is a pseudo-random generator. More precisely, it's a linear congruential generator.

You stated you are curious about the "magic" numbers. Well, they are really mostly arbitrarily-chosen from a practically infinite set of numbers. Often, prime coefficients are used (especially as the divisor) for number theoretic reasons (primarily in order to avoid very obvious repetitions in the generated pattern); however, naive LCGs like this produce very low quality PRNs, so if there's a serious need for good-quality pseudo-randomness, it's quite pointless to try and tune a LCG – just use a better PRNG algorithm.

like image 71
The Paramagnetic Croissant Avatar answered Nov 10 '22 11:11

The Paramagnetic Croissant


It's not really a random number generator, but a pseudo-random number based of a provided seed. Resetting the seed will reset getNextValue and give consistent output.

As the comment mentions, this code is based on the The Central Randomizer. Apparently this code was created because Math.random did not work in the now-archaic Netscape 2. In turn, this implementation is based on existing pseudo-random number generators. See Original source of (seed * 9301 + 49297) % 233280 random algorithm? for more information on the origins of this algorithm.

Technically Math.random is also pseudo-random, but you do not have control over the seed, so this code does have a potentially useful property. If you give it a consistent seed, you will get consistent output across reloads.

like image 1
Alexander O'Mara Avatar answered Nov 10 '22 12:11

Alexander O'Mara