admin管理员组文章数量:1426458
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)
本文标签: javascriptHow to get a cryptographically strong number in the range 01)Stack Overflow
版权声明:本文标题:javascript - How to get a cryptographically strong number in the range [0,1)? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745463616a2659434.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论