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.
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.
- Related question on crypto.SE. – Ilmari Karonen Commented Mar 3, 2018 at 14:06
1 Answer
Reset to default 9Why not simplify things
function cryptoRandom() {
return window.crypto.getRandomValues(new Uint32Array(1))[0] / 0x100000000;
}
What's going on here?
- Assume
window.crypto.getRandomValues
will giving us truely random bits - Ask for 32 bits (unsigned integer
i
) - The
min
ium value ofi
is0x00000000
(or0
) - The
max
imum value ofi
is0xFFFFFFFF
(or4294967295
) - Transform these points onto the range you want;
(i - min) / (max + 1)