Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random float number in given specific range of numbers using Bash

can someone help me in generating random float number with given specific range of number in bash (shell). I found below command but is their any other option ? (using awk or $rand commands.)

jot -p2  0 1
like image 288
Aamir Khan Avatar asked May 15 '18 21:05

Aamir Khan


3 Answers

If you have GNU coreutils available, you could go with:

seq 0 .01 1 | shuf | head -n1

Where 0 is the start (inclusive), .01 is the increment, and 1 is the end (inclusive).

like image 71
Thor Avatar answered Oct 16 '22 12:10

Thor


Without any external utilities, generate random real between 3 and 16.999:

a=3
b=17
echo "$((a+RANDOM%(b-a))).$((RANDOM%999))"
like image 25
Mark Setchell Avatar answered Oct 16 '22 14:10

Mark Setchell


To generate 1 random floating point number between 3 and 17:

$ awk -v min=3 -v max=17 'BEGIN{srand(); print min+rand()*(max-min+1)}'
16.4038

To generate 5 random floating point numbers between 3 and 17:

$ awk -v min=3 -v max=17 -v num=5 'BEGIN{srand(); for (i=1;i<=num;i++) print min+rand()*(max-min+1)}'
15.1067
4.79238
3.04884
11.3647
15.1132

Massage to suit.

like image 4
Ed Morton Avatar answered Oct 16 '22 12:10

Ed Morton