Skip to content

Instantly share code, notes, and snippets.

@queviva
Last active October 10, 2024 21:49
Show Gist options
  • Save queviva/dc42292dc4230fa1eda6d52b26cd30f8 to your computer and use it in GitHub Desktop.
Save queviva/dc42292dc4230fa1eda6d52b26cd30f8 to your computer and use it in GitHub Desktop.
random floats from zero-to-one using crypto.getRandomValues()
const crandomVal = () => (crypto.getRandomValues(new Uint32Array(1))[0] / (2 ** 32)) ;
const crandomInt = (a=1) => ~~((crypto.getRandomValues(new Uint32Array(1))[0] / (2 ** 32)) * a);
const crandomArr = (a=1, b=1) => [...crypto.getRandomValues(new Uint32Array(a))].map(v => (v / 2**32) * b);
const crandomIntArr = (a=1, b=1) => [...crypto.getRandomValues(new Uint32Array(a))].map(v => ~~((v / 2**32) * b));
@queviva
Copy link
Author

queviva commented Jul 9, 2022

this uses the crypto method of generating random values to return floating point values between zero and one; it functions like Math.random() but uses the crypto's values

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment