Reputation: 33
How can I do random sampling within interval with given interval? For example, I want to do single random sampling between 1 to 10 but with each interval is 0.5. So when I do the sampling, it will give me value for example 5.5 or 2 or 8.5.
I have tried with np.random.random_integers(1,10) but this just give me integers value. Your help is kindly appreciated.
Upvotes: 3
Views: 2314
Reputation: 1756
You can use linspace
from the numpy
library. Here is an example:
>>> import numpy
>>> numpy.linspace(0.5, 10, 20)
array([ 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5,
5. , 5.5, 6. , 6.5, 7. , 7.5, 8. , 8.5, 9. ,
9.5, 10. ])
>>> range_of_numbers = numpy.linspace(0.5, 10, 20)
>>> random_number = numpy.random.choice(range_of_numbers, size=1)
>>> print random_number
[ 9.5]
The result set of linspace
is in an array, but you can easily work with that further if need be. Here is some more documentation on using linspace
.
EDIT
Another option is to use Pylab's frange
library. It's a wrapper around matplotlib
, but worth looking into for the solution you are trying to achieve. Here's an example of using frange
:
>>> import pylab
>>> pylab.frange(0.5,10,0.5)
array([ 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5,
5. , 5.5, 6. , 6.5, 7. , 7.5, 8. , 8.5, 9. ,
9.5, 10. ])
Here's some more documentation around frange
.
Additional Notes
While you could use arange
, keep in mind that it leads to floating point errors. The NumPy documentation recommends using linspace
to avoid the floating point errors. Also, arange
and linspace
have different APIs.
Upvotes: 1
Reputation: 9010
You can write your own function which scales, generates a random integer, and then unscales.
from math import floor, ceil
from random import randint
def random_step(low, high, step):
low_scaled = ceil(float(low)/step)
high_scaled = floor(float(high)/step)
return randint(low_scaled, high_scaled) * step
print random_step(3.0, 8.5, 0.5) # 4.5
The output will always be a multiple of step
.
Upvotes: 4
Reputation: 16958
You can do:
from random import randrange
random_number = randrange(2,21)*.5
Upvotes: 0