如何从随机数生成器返回中间位? [英] How to return middle bits from random number generator?

查看:36
本文介绍了如何从随机数生成器返回中间位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 random_rand() 函数,它产生一个介于 0 和 RANDOM_RAND_MAX 之间的随机数.RANDOM_RAND_MAX 定义为 65535.

I have a random_rand() function which produces a random number between 0 and RANDOM_RAND_MAX. RANDOM_RAND_MAX is defined to be 65535.

我想使用 random_rand() 结果中的中间位而不是最低位,以便我可以更好地进行随机化.

I would like to use the middle bits from the result of random_rand() instead of lowest-order bits so that I can make the randomiztion better.

你能告诉我一个快速的方法吗.

Could you please show me a quick way to do this.

谢谢

推荐答案

这太调皮了.

线性同余生成器的工作方式是最随机"的部分包含低位.几十年前一个非常著名的 rand 的 IBM 实现在绘图之后交换了最高和最低位作为最后的繁荣 - 这被发现完全破坏了生成器!

Linear congruential generators work in such a way that the "most random" part comprises the lower order bits. A very famous IBM implementation of rand a couple of decades ago swapped the highest and lowest bits round after a drawing as a final flourish - this was found to completely ruin the generator!

所以保持简单.使用 % 运算符或按位 & 生成随机数并提取最低有效位:虽然这会引入统计偏差,但效果并不比生成器本身差.

So keep things simple. Generate your random number and extract the least significant bits using the % operator or a bitwise &: although this introduces statistical bias, the effects are no worse than the generator itself.

无论您最终做什么,始终对您的生成器进行一些统计检查,以确保它具有足够的统计属性.在撰写本文时,似乎最佳"的生成方案是 Mersenne Twister.

Whatever you end up doing, always run some statistical checks on your generator to make sure it has adequate statistical properties. At the time of writing, the generation scheme that seems to be the "best one" is the Mersenne Twister.

(如果您真的想要中间位,那么使用按位右移运算符>>&的混合.)

(If you really want the middle bits, then use a mixture of the bitwise right shift operator >> and &.)

这篇关于如何从随机数生成器返回中间位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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