Uniform random positive decimal number in bash

北慕城南 提交于 2020-01-05 04:33:13

问题


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

回答1:


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.

Try this:

echo "0.$(( ($RANDOM%500) + 500))"

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

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



来源:https://stackoverflow.com/questions/46128991/uniform-random-positive-decimal-number-in-bash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!