6

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
jww
  • 97,681
  • 90
  • 411
  • 885
Aamir Khan
  • 101
  • 1
  • 7
  • Does this answer your question? [Random number between range in shell](https://stackoverflow.com/questions/4673830/random-number-between-range-in-shell) – Peter O. Feb 23 '21 at 21:41

3 Answers3

13

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

vallentin
  • 23,478
  • 6
  • 59
  • 81
Thor
  • 45,082
  • 11
  • 119
  • 130
7

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

a=3
b=17
echo "$((a+RANDOM%(b-a))).$((RANDOM%999))"
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
4

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.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
  • I've tried your command and the output is exceeding the maximum value, could you please help me out with this. For your Reference below is the output which i've got. `awk -v min=6.50 -v max=8.45 'BEGIN{srand(); print min+rand()*(max-min+1)}'` `9.21745` – Aamir Khan May 30 '18 at 21:36
  • 1
    The problem is the `+1` - that's too high a value to compensate for rand() never reaching `1` when you're not working with integers. Try `awk -v min=6.50 -v max=8.45 'BEGIN{srand(); print min+rand()*int(1000*(max-min)+1)/1000}'` instead - that should be good to 3 decimal points. – Ed Morton May 31 '18 at 05:15
  • Thank you! I've been looking for solution to this and your answer works nicely. But one question though, is it possible to limit the result to ending in 0.5. So the result would be like : 1.5, 12.5, 0.5,.... – KMC Oct 05 '18 at 15:52
  • Of course but this answer is 3 years old and I'm not going to revisit it so just ask a new question if you need help. – Ed Morton Oct 05 '18 at 16:09