如何在不使用 AWK 或 bc 的情況下,在一個范圍內生成均勻分布的亂數,并在 bash 中使用 pe、2 或 5 個小數位?
Bash 通常只支持整數。但是,bash 中可以使用帶小數位的數字,例如使用命令 sleep: sleep 1.23456 # sleep time in s
給出以下示例,它可以使用 bash 生成 0 到 10 范圍內的均勻分布的不帶小數位的亂數。
ug_rnd=0
og_rnd=10
rnd="$((0x$(dd if=/dev/urandom of=/dev/stdout bs=4 count=1 status=none | xxd -p)))"
my_rnd=$((rnd%(og_rnd-ug_rnd 1) ug_rnd));
echo "$my_rnd"
sleep "$my_rnd"
uj5u.com熱心網友回復:
假設您當前正在和之間生成亂數0,10并且您想要添加 2 個小數位。
考慮在0和1000( 10 * 10^2)之間生成亂數,將結果分成 2x 塊,然后用小數拼湊在一起。
一個粗略的例子:
注意:添加了 Kamilcuk 的評論:printf用于處理左填充數字0's
$ x=735 # assume this is our random number (between 0 and 1000)
$ absx="${x#-}" # if x is negative we need to strip off '-' for 2nd calculation to keep from generating "-7.-35"
$ printf -v newx "%d.d" "$(( x / 100 ))" "$(( absx % 100 ))"
$ echo "${newx}"
7.35
$ time sleep "${newx}"
real 0m7.375s
user 0m0.000s
sys 0m0.015s
如果 OP 需要 4 個小數位,則在0和100000( 10 x 10^4)之間生成一個亂數,并將100條目(在newxsplit-n-piece-together 操作中)替換為10000.
向當前代碼添加一些邏輯以計算出乘數 ( 10^<number_of_decimals>)、設定og_rnd=$((10*<multiplier))并替換為 split-n-piece-together 操作中100的<multiplier>變數應該不會太難。
uj5u.com熱心網友回復:
在你們談論它的時候我玩了這個。我的建議是相似的,有點...
range=100 scale=5; w=$((${#range} scale));
printf "%0$w.${scale}f\n" "$((RANDOM%$range)).$(
s=$scale; while ((s--)); do printf "%s" $((RANDOM)); done
)"
不過,我仍然認為這awk是一個更好的解決方案。
uj5u.com熱心網友回復:
檢查最佳投票答案:
好看:
$ x=735 # assume this is our random number (between 0 and 1000)
$ absx="${x#-}" # if x is negative we need to strip off '-' for 2nd calculation to keep from generating "-7.-35"
$ printf -v newx "%d.d" "$(( x / 100 ))" "$(( absx % 100 ))"
$ echo "${newx}"
7.35
也好看:
$ x=-735 # assume this is our random number (between 0 and 1000)
$ absx="${x#-}" # if x is negative we need to strip off '-' for 2nd calculation to keep from generating "-7.-35"
$ printf -v newx "%d.d" "$(( x / 100 ))" "$(( absx % 100 ))"
$ echo "${newx}"
-7.35
錯誤結果:
$ x=-50 # assume this is our random number (between 0 and 1000)
$ absx="${x#-}" # if x is negative we need to strip off '-' for 2nd calculation to keep from generating "-7.-35"
$ printf -v newx "%d.d" "$(( x / 100 ))" "$(( absx % 100 ))"
$ echo "${newx}"
0.50
給出錯誤結果的范圍:
輸入:
x=-1 ... - 99
輸出:
newx= 0.01 ... 0.99
uj5u.com熱心網友回復:
它的可能和簡單:由 bash 創建的在一個范圍內均勻分布的亂數和小數位。
ug_rnd=-10
og_rnd=10
decimal_places=5
decimal_places_faktor=$((10**decimal_places))
ug_rnd_new=$((ug_rnd*decimal_places_faktor))
og_rnd_new=$((og_rnd*decimal_places_faktor))
rnd="$((0x$(dd if=/dev/urandom of=/dev/stdout bs=4 count=1 status=none | xxd -p)))"
my_rnd=$((rnd%(og_rnd_new-ug_rnd_new 1) ug_rnd_new));
echo "$my_rnd"
echo
echo
echo "var_left"
var_left=${my_rnd::$((${#my_rnd}-decimal_places))}
echo "$var_left"
echo
echo
echo "var_right"
var_right=${my_rnd:$((${#my_rnd}-decimal_places))}
echo "$var_right"
echo
echo
echo "Equal distributed random count incl. decimal places in bash"
echo "$var_left.$var_right"
echo
echo
$ -2.23559 # Can generate positive an negative values.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/341795.html
