问题描述
我想使用ping进行随机的ICMP通信.我需要在代码中为时间参数设置一个介于0.5到1之间的随机十进制数.您能告诉我如何制作统一的随机十进制数吗?我的代码只能使一个整数.谢谢
I would like to make a random ICMP traffic using ping. I need to make a random decimal number between 0.5 to 1 for time parameter in my code. Could you please show me how to make uniform random decimal number? My code just can make a integer number. Thanks
#!/bin/bash
for ((i = 0; i <=100; i++))
do
#need to have random number between 0.5 to 1 for time
time=$(($RANDOM%5+1))
num=$(($RANDOM%5+1))
ping -c $num -i $time 10.0.0.2
done
推荐答案
bash
实际上不是做十进制数,只能是整数,但是您可以通过生成来伪造十进制数整数并将小数点放在开头.
bash
doesn't actually do decimal number, only integers, but you can fake decimals by generating integers and putting a decimal point at the start.
尝试一下:
echo "0.$(( ($RANDOM%500) + 500))"
关于均匀性,您可以生成10,000个这样的样本:
As regards it being uniform, you can generate 10,000 samples like this:
for ((i=1;i<10000;i++)) ; do echo "0.$(( ($RANDOM%500) + 500))" ; done > data
然后使用 gnuplot 绘制频率分布,如下所示:
And then plot the frequency distribution with gnuplot like this:
gnuplot --persist <<EOF
# Make some suitable labels.
set title "Number Distribution"
set xlabel "Value"
set ylabel "Count"
set style histogram clustered gap 1
set style fill solid border -1
binwidth=0.01
set boxwidth binwidth
bin(x,width)=width*floor(x/width) + binwidth/2.0
plot 'data' using (bin(\$1,binwidth)):(1.0) smooth freq with boxes
EOF
这篇关于bash中的均匀随机正十进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!