Last active
January 3, 2024 18:55
-
-
Save pilcrowonpaper/e01f0f58d8f5154211fd653059ab2258 to your computer and use it in GitHub Desktop.
Cryptographically strong Math.random(). Generate cryptographically strong random float between 0-1. Uses 52 bits instead of 32.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function random(): number { | |
const buffer = new ArrayBuffer(8); | |
const bytes = crypto.getRandomValues(new Uint8Array(buffer)); | |
// sets the exponent value (11 bits) to 01111111111 (1023) | |
// since the bias is 1023 (2 * (11 - 1) - 1), 1023 - 1023 = 0 | |
// 2^0 * (1 + [52 bit number between 0-1]) = number between 1-2 | |
bytes[0] = 63; | |
bytes[1] = bytes[1] | 240; | |
return new DataView(buffer).getFloat64(0) - 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment