Skip to content

Instantly share code, notes, and snippets.

@pilcrowonpaper
Last active January 3, 2024 18:55
Show Gist options
  • 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