Skip to content

Instantly share code, notes, and snippets.

@pilcrowOnPaper
Last active January 3, 2024 18:55
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pilcrowOnPaper/e01f0f58d8f5154211fd653059ab2258 to your computer and use it in GitHub Desktop.
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.
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