问题描述
我想生成一个从0到3的随机十进制数,结果应如下所示:
I want to generate a random decimal number from 0 to 3, the result should look like this:
0.2
1.5
2.9
我知道的唯一命令是:
echo "0.$(( ($RANDOM%500) + 500))"
,但这始终会生成 0.xxx
.我该怎么办?
but this always generates 0.xxx
. How do I do that ?
推荐答案
Bash不支持非整数.您刚创建的代码段会生成一个介于500到999之间的随机数,然后在"0"之后打印出来.使它看起来像一个实数.
Bash has no support for non-integers. The snippet you have just generates a random number between 500 and 999 and then prints it after "0." to make it look like a real number.
有很多方法可以在bash中执行类似的操作(分别生成整数和十进制部分).为了确保最大程度的平均分配,我只需要确定小数点后要多少位数,并选择一个精度相同的随机整数,然后将小数点后的数字打印在正确的位置即可.例如,如果只希望半开范围[0,3)的小数点后一位,则可以生成0到30之间的整数,然后打印出由句点分隔的十位数和十位数:
There are lots of ways to do something similar in bash (generating the integer and decimal parts separately). To ensure a maximally even distribution, I would just decide how many digits you want after the decimal and pick a random integer with the same precision, then print the digits out with the decimal in the right place. For example, if you just want one digit after the decimal in the half-open range [0,3), you can generate an integer between 0 and 30 and then print out the tens and ones separated by a period:
(( n = RANDOM % 30 ))
printf '%s.%s\n' $(( n / 10 )) $(( n % 10 ))
如果要在小数点后两位,请在RANDOM分配中使用%300
,在 printf
的两个表达式中使用100.依此类推.
If you want two digits after the decimal, use % 300
in the RANDOM assignment and 100 in the two expressions on the printf
. And so on.
或者,请参见下面的答案,以获得使用其他非bash内置工具的解决方案:
Alternatively, see the answer below for a number of solutions using other tools that aren't bash builtins:
https://stackoverflow.com/a/50359816/2836621
这篇关于如何使用bash生成从0到3的随机十进制数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!