节点:使用crypto.randomBytes生成6位数的随机数 [英] Node: Generate 6 digits random number using crypto.randomBytes

查看:461
本文介绍了节点:使用crypto.randomBytes生成6位数的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于1000000并非2的幂,因此随机地产生从0999999的精确值的正确方法是什么?

What is the correct way to generate exact value from 0 to 999999 randomly since 1000000 is not a power of 2?

这是我的方法:

  1. 使用crypto.randomBytes生成3个字节并转换为hex
  2. 使用前5个字符转换为整数(最大为fffff == 1048575> 999999)
  3. 如果结果> 999999,请从步骤1重新开始
  1. use crypto.randomBytes to generate 3 bytes and convert to hex
  2. use the first 5 characters to convert to integer (max is fffff == 1048575 > 999999)
  3. if the result > 999999, start from step 1 again

它将以某种方式创建递归函数.它在逻辑上是否正确,是否会引起性能问题?

It will somehow create a recursive function. Is it logically correct and will it cause a concern of performance?

推荐答案

有几种方法可以从随机位中提取一定范围内的随机数. NIST特殊出版物800-90A修订版1中描述了一些常见的问题:建议使用确定性随机位生成器生成随机数

There are several way to extract random numbers in a range from random bits. Some common ones are described in NIST Special Publication 800-90A revision 1: Recommendation for Random Number Generation Using Deterministic Random Bit Generators

尽管此标准是关于确定性随机位生成的,但是有一个有用的附录称为 A.5将随机位转换为随机数,它描述了三种有用的方法.

Although this standard is about deterministic random bit generations there is a helpful appendix called A.5 Converting Random Bits into a Random Number which describes three useful methods.

描述的方法是:

  • A.5.1简单丢弃方法
  • A.5.2复杂丢弃方法
  • A.5.3简单模块化方法

它们中的前两个不是确定性的,而是生成一个完全没有偏差的数字.它们基于拒绝抽样.最后一个是时间常数和确定性的,但具有非零(但可以忽略)的偏差.不过,要实现可忽略的偏差,还需要相对大量的随机性.

The first two of them are not deterministic but generate a number with no bias at all. They are based on rejection sampling. The last one is time constant and deterministic but has non-zero (but negligible) bias. It requires a relatively large amount of additional randomness to achieve the negligible bias though.

您的算法显然是简单丢弃方法(通常称为拒绝采样")的一种版本,因此很好.

当然,您应该使用通用方法,该方法对于任何N值都有效.在这种情况下,应考虑在简单丢弃方法上考虑复杂丢弃方法或简单模块化方法.还有其他更复杂的算法甚至更有效,但是通常使用这两种方法都可以.

Of course you should rather use a generic method that is efficient given any value of N. In that case the Complex Discard Method or Simple Modular Method should be considered over the Simple Discard Method. There are other, much more complex algorithms that are even more efficient, but generally you're fine when using either of these two.

请注意,在生成范围为[0, N)的随机数时,首先检查N是否为2的幂通常是有益的.如果N 是2的幂,则无需使用任何可能昂贵的计算;否则,将不再使用.只需使用随机位或字节生成器中所需的位即可.

Note that it is often beneficial to first check if N is a power of two when generating a random in the range [0, N). If N is a power of two then there is no need to use any of these possibly expensive computations; just use the bits you need from the random bit or byte generator.

这篇关于节点:使用crypto.randomBytes生成6位数的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆