I've been trying to create a function that will return a random decimal number between 0 (inclusive) and 1 (exclusive) via the Window.crypto.getRandomValues() function. Currently, my code is as follows:
var rand = function(){
var ra = window.crypto.getRandomValues(new Uint32Array(1))[0];
function dec(n,m){
return (n>=0&&n<=1)?n:dec(n/m,m);
}
return dec(ra,8);
}
My problem is that this isn't uniformly distributed; it tends to be between .2 and .7, and rarely falls under .2 and over .7. Is there a better way to use the .getRandomValues() method to obtain a number like that of the Math.random() function?
I am not using the .random() method because I wish to have secure numbers for what I am trying to perform.
Why not simplify things
function cryptoRandom() {
return window.crypto.getRandomValues(new Uint32Array(1))[0] / 0x100000000;
}
What's going on here?
window.crypto.getRandomValues will giving us truely random bitsi)minium value of i is 0x00000000 (or 0)maximum value of i is 0xFFFFFFFF (or 4294967295)(i - min) / (max + 1)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With