How to generate a random decimal number from 0 to 3 with bash?

巧了我就是萌 提交于 2021-02-05 08:12:09

问题


I want to generate a random decimal number from 0 to 3, the result should look like this:

0.2
1.5
2.9

The only command I know is:

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

but this always generates 0.xxx. How do I do that ?


回答1:


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.

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 ))

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.

Alternatively, see the answer below for a number of solutions using other tools that aren't bash builtins:

https://stackoverflow.com/a/50359816/2836621




回答2:


$RANDOM gives random integers in the range 0..32767

Knowing this, you have many options. Here are two:

  1. Using bc:

    $ bc <<< "scale=3; 3 * $RANDOM / 32767"
    2.681
    
  2. Constructing a number with two $RANDOMs:

    $ echo "$(( $RANDOM % 3 )).$(( $RANDOM % 999 ))"
    0.921
    

I have limited the precision to 3 decimal digits. Increasing/decreasing it should be trivial.



来源:https://stackoverflow.com/questions/50777586/how-to-generate-a-random-decimal-number-from-0-to-3-with-bash

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