Random float numbers in BASH

Hi people :slight_smile:

I'm learning shell scripting using bash and I want to generate 4 floating point number with 5 decimal places and write them to a file and a variable. I've done all this except the $RAMDOM enviroment variable does not generate a float number but a integrer.

I hope you could explain why to lead me to a solution.
Thnak you all in advance.

PS: script so far

#!/bin/bash

#: Title		: randomFloats
#: Date			: 2011-03-27
#: Author		: pharaoh
#: Version		: 1.0 
#: Discription	        : Generate a 4 float numbers with 5 decimal places and write them to a file and a variable 


listFloats=0.0
for i in $(seq 0 3)
do
    aux=$[($RANDOM % 15000)]
	printf -v aux "%.5f" ${aux}
	
	#In the first iteration it just set the variable, in the others it append
	if [ ${i} -eq 0 ]
	then
		listFloats=${aux}
		printf ${aux} > randomFloats.txt
	else 
		listFloats="${listFloats} ${aux}"
		printf ${aux} >> randomFloats.txt
	fi
done

printf "%s\n" ${listFloats}

BASH doesn't support floating point numbers.

How about generating random digits 0-9 and appending that into a floating point number?

1 Like

As Corona688 says generate the digits for the 5 decimal places. I'd pick 3 digits then 2 as RANDOM won't go high enough to pick all 5

#!/bin/bash
listFloats=0.0
for i in {0..3}
do
   aux=$(printf "0.%03d%02d" $(( $RANDOM % 1000 )) $(( $RANDOM % 100)))
   if [ ${i} -eq 0 ]
   then
   ...
1 Like

Thank you guys! I didn't knew that bash don't support floating point numbers.
That was very helpful.

---------- Post updated at 02:53 PM ---------- Previous update was at 02:52 PM ----------

Man you are a Genius. I like your answer, thank you for passing the knowledge.