Random numbers — Math.random for games, crypto for secrets¶
Level: 201 · for anyone who needs a random number, or a secret one
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.
One line: Math.random is a pseudo-random generator seeded once per process: node --random-seed=42 prints the same number on every run, while crypto.randomUUID() still differs, because the crypto functions use a secure generator the seed does not touch, the only kind for tokens and passwords.
Keywords: Math.random, crypto.getRandomValues, crypto.randomUUID, randomInt
What the finished page will answer¶
- Does
node --random-seed=42makeMath.random()print the same sequence on every run, and does it change whatcrypto.randomUUID()returns? - Why does
Math.round(Math.random() * 2)produce 1 about twice as often as 0 or 2, and which formula gives a fair integer in a range? - What do
crypto.getRandomValues,crypto.randomUUIDandrandomIntfromnode:cryptoreturn? - Why does
crypto.getRandomValues(new Uint8Array(65537))throw, and why does aFloat64Arrayfail too?
Examples it will need¶
-
random_numbers_seed_sh.sh— two runs with--random-seed=42compared, then two runs ofcrypto.randomUUID()compared, printing only same or different so the output is stable -
random_numbers_rounding_bias_sh.sh— a count of 30,000 rolls made withMath.round(Math.random() * 2)and withMath.floor(Math.random() * 3), under a fixed--random-seedso the counts repeat -
random_numbers_crypto_js.js— the length and type of whatgetRandomValues,randomUUIDandrandomIntreturn, and theQuotaExceededErrorfor 65,537 bytes
See also¶
- Typed arrays and
ArrayBuffer— the typed arraygetRandomValuesfills - Which features your Node has — engine options such as
--random-seed, listed bynode --v8-options - Rounding and formatting —
Math.flooragainstMath.roundwhen mapping a float to a range - Cryptography: random is not secrets ↗ — the same split in Python:
randomagainstsecrets - Rust: Randomness:
stdhas none ↗ — in Rust, the standard library ships no random generator at all