Generating several random numbers within a range

I want to generate, say 10 random numbers between 100 and 200 (both included). How do I make it with rand?


Solution 1:

If you mean the rand from the rand package (as opposed to the one from OpenSSL), it doesn't support a lower bound, only an upper bound. What you can do is the shift-lower-bound-to-zero-then-add-lower-bound trick:

$ rand -N 10 -M 100 -e -d '\n' | awk '{$0 += 100}1'
170
180
192
168
169
170
117
180
167
142
  • -N is the number of random numbers you need
  • -M would be the upper bound of the numbers rand outputs, so (max - min = 100)
  • -e -d '\n' sets the delimiter to a newline. That's for convenience of processing by awk.

The awk code then takes each line and adds 100 to it.

Solution 2:

Using python:

#!/usr/bin/env python2
import random
for i in range(10):
    print random.randint(100, 200)

Output :

187
123
194
190
124
121
191
103
126
192

Here I have used the random module of python to generate 10 (range(10)) random integers between 100 and 200 (included) (random.randint(100, 200)).

Solution 3:

Here's a Perl way:

$ perl -le 'print 100+int(rand(101)) for(1..10)'

129
197
127
167
116
134
143
134
122
117
Or, on the same line:

$ perl -e 'print 100+int(rand(101))." " for(1..10); print "\n"'
147 181 146 115 126 116 154 112 100 116 

You could also use /dev/urandom (adapted from here):

$ for((i=0;i<=10;i++)); do 
    echo $(( 100+(`od -An -N2 -i /dev/urandom` )%(101))); 
done
101
156
102
190
152
130
178
165
186
173
143

Solution 4:

With shuf from GNU coreutils:

$ shuf -i 100-200 -n 10
159
112
192
140
166
121
135
120
198
139