生成大于特定数字的随机数
在高级 Bash 脚本指南章节9.3。 $RANDOM:生成随机整数
它说明了如何生成大于特定数字的随机数:
FLOOR=200
number=0 #initialize
while [ "$number" -le $FLOOR ]
do
number=$RANDOM
done
echo "Random number greater than $FLOOR --- $number"
echo
然后评论说:
# Let's examine a simple alternative to the above loop, namely
# let "number = $RANDOM + $FLOOR"
# That would eliminate the while-loop and run faster.
# But, there might be a problem with that. What is it?
我认为它仍然是随机性并且大于$FLOOR,所以我不知道这是什么问题。
In Advanced Bash-Scripting Guide Chaper 9.3. $RANDOM: generate random integer
It illustrates how to generate a random number greater than a specific number:
FLOOR=200
number=0 #initialize
while [ "$number" -le $FLOOR ]
do
number=$RANDOM
done
echo "Random number greater than $FLOOR --- $number"
echo
And then the comment says:
# Let's examine a simple alternative to the above loop, namely
# let "number = $RANDOM + $FLOOR"
# That would eliminate the while-loop and run faster.
# But, there might be a problem with that. What is it?
I think it is still randomness and greater than $FLOOR
, so I don't know what the problem it is.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
$RANDOM
的结果永远不会大于 32767。但是,如果您期望结果介于$FLOOR
和 32767 之间,请添加$FLOOR
code> 和$RANDOM
不会帮助你。如果您将任何大于 32767 的值视为 32767,那么您将使您的生成器更具可预测性。通过(32767 - $FLOOR)
修改结果并添加$FLOOR
并不是那么糟糕。另一个不带循环的解决方案是使用 $RANDOM * ( 32767 - $FLOOR ) / 32767 + $FLOOR 但 bash 缺乏浮点数学,并且可能由于舍入错误而错过几个数字。$RANDOM
won't ever have a result greater than 32767. However, if you're expecting a result between$FLOOR
and 32767, adding$FLOOR
and$RANDOM
won't help you. If you treat any value greater than 32767 as 32767 then you're making your generator more predictable. Not quite as bad is modding your result by(32767 - $FLOOR)
and adding$FLOOR
. Another solution without looping is to use$RANDOM * ( 32767 - $FLOOR ) / 32767 + $FLOOR
but bash lacks floating point math and may miss a couple numbers due to rounding error.问题是你可以生成 0,然后你的数字将等于 FLOOR。
The problem is that you could generate 0 and then your number would be equal to FLOOR.
问题可能来自溢出。假设您的 prng 生成一个 0 到 maxint 之间的数字。如果您只是简单地添加下限,那么当相加得到的数字大于 maxint 时会发生什么?当然,您可以简单地拒绝这些数字,但这会产生与您提出的算法相同的算法。
根据底线的不同,可以使用一些技巧来最大程度地减少拒绝。例如,如果所需的数字大于 maxint / 2,您可以在测试拒绝之前系统地设置较高位。
The problem probably comes from overflow. Let say your prng generate a number between 0 and maxint. If you simply add the floor, what occur when the addition gives a number greater than maxint? Of course, you could simply reject those numbers, but it would result in the same algorithm as the one you proposed.
Depending on what is the floor, some tricks could be used to minimize rejection. For example, if needed number is greater than maxint / 2, you could systematically set the higher bit before testing for rejection.