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 ?
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 ?
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:
$RANDOM
gives random integers in the range 0..32767
Knowing this, you have many options. Here are two:
Using bc:
$ bc <<< "scale=3; 3 * $RANDOM / 32767"
2.681
Constructing a number with two $RANDOM
s:
$ echo "$(( $RANDOM % 3 )).$(( $RANDOM % 999 ))"
0.921
I have limited the precision to 3 decimal digits. Increasing/decreasing it should be trivial.