gpt4 book ai didi

bash - 在 bash 中使用 $RANDOM + $FLOOR 有什么问题?

转载 作者:行者123 更新时间:2023-11-29 09:43:47 25 4
gpt4 key购买 nike

正在阅读:http://www.tldp.org/LDP/abs/html/randomvar.html

#  If you need a random integer greater than a lower bound,
#+ then set up a test to discard all numbers below that.

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?

我无法对上一条评论中的问题给出一个像样的答案。这就是我总是用其他语言(C/C++、Pascal)生成伪随机数的方式,并且没有任何问题——这是否只与 Bash 相关?

最佳答案

在您的随机数生成器可以为您提供刚好低于溢出点的值的编程语言中,后一个代码会有一个错误,其中项目在 MAXINT - FLOORMAXINT 会溢出。

Bash 没有这个错误,但您正在阅读的引用资料显然是在没有意识到这一点的情况下编写的。

关于bash - 在 bash 中使用 $RANDOM + $FLOOR 有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23435810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com