Javascript:使用 crypto.getRandomValues 生成一个范围内的随机数 [英] Javascript: Generate a random number within a range using crypto.getRandomValues
问题描述
我知道您可以使用此函数在 JavaScript 中生成一个范围内的随机数:
I understand you can generate a random number in JavaScript within a range using this function:
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
由 Ionuț G. Stan 提供此处.
我想知道的是,您是否可以使用 crypto.getRandomValues() 而不是 Math.random().我希望能够生成一个介于 0 和 10 之间的数字,或者 0 - 1,甚至 10 - 5000 包括在内.
What I want to know is if you can generate a better random number in a range using crypto.getRandomValues() instead of Math.random(). I would like to be able to generate a number between 0 and 10 inclusive, or 0 - 1, or even 10 - 5000 inclusive.
您会注意到 Math.random() 生成的数字类似于:0.8565239671015732.
You'll note Math.random() produces a number like: 0.8565239671015732.
getRandomValues API 可能返回如下内容:
The getRandomValues API might return something like:
- 231 与
Uint8Array(1)
- 54328 与
Uint16Array(1)
- 355282741 和
Uint32Array(1)
.
- 231 with
Uint8Array(1)
- 54328 with
Uint16Array(1)
- 355282741 with
Uint32Array(1)
.
那么如何将其转换回十进制数,以便我可以使用上述相同的范围算法?还是我需要一个新的算法?
So how to translate that back to a decimal number so I can keep with the same range algorithm above? Or do I need a new algorithm?
这是我尝试过的代码,但效果不佳.
Here's the code I tried but it doesn't work too well.
function getRandomInt(min, max) {
// Create byte array and fill with 1 random number
var byteArray = new Uint8Array(1);
window.crypto.getRandomValues(byteArray);
// Convert to decimal
var randomNum = '0.' + byteArray[0].toString();
// Get number in range
randomNum = Math.floor(randomNum * (max - min + 1)) + min;
return randomNum;
}
在低端(范围 0 - 1),它返回的 0 多于 1.使用 getRandomValues() 执行此操作的最佳方法是什么?
At the low end (range 0 - 1) it returns more 0's than 1's. What's the best way to do it with getRandomValues()?
非常感谢
推荐答案
最简单的方法可能是拒绝抽样(参见 http://en.wikipedia.org/wiki/Rejection_sampling).例如,假设 max - min
小于 256:
The easiest way is probably by rejection sampling (see http://en.wikipedia.org/wiki/Rejection_sampling). For example, assuming that max - min
is less than 256:
function getRandomInt(min, max) {
// Create byte array and fill with 1 random number
var byteArray = new Uint8Array(1);
window.crypto.getRandomValues(byteArray);
var range = max - min + 1;
var max_range = 256;
if (byteArray[0] >= Math.floor(max_range / range) * range)
return getRandomInt(min, max);
return min + (byteArray[0] % range);
}
这篇关于Javascript:使用 crypto.getRandomValues 生成一个范围内的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!