Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sampling random floats on a range in numpy

People also ask

How do you generate random numbers between ranges in NumPy?

An array of random integers can be generated using the randint() NumPy function. This function takes three arguments, the lower end of the range, the upper end of the range, and the number of integer values to generate or the size of the array.

How do I randomly sample from a NumPy array?

choice() function is used to get random elements from a NumPy array. It is a built-in function in the NumPy package of python. Parameters: a: a one-dimensional array/list (random sample will be generated from its elements) or an integer (random samples will be generated in the range of this integer)

How do I select a random number in NumPy?

The choice() method allows you to generate a random value based on an array of values. The choice() method takes an array as a parameter and randomly returns one of the values.


The uniform distribution would probably do what you are asking.

np.random.uniform(5,10) # A single value
np.random.uniform(5,10,[2,3]) # A 2x3 array

without numpy you can do this with the random module.

import random
random.random()*5 + 10

will return numbers in the range 10-15, as a function:

>>> import random
>>> def random_float(low, high):
...     return random.random()*(high-low) + low
...
>>> random_float(5,10)
9.3199502283292208
>>> random_float(5,10)
7.8762002129171185
>>> random_float(5,10)
8.0522023132650808

random.random() returns a float from 0 to 1 (upper bound exclusive). multiplying it by a number gives it a greater range. ex random.random()*5 returns numbers from 0 to 5. Adding a number to this provides a lower bound. random.random()*5 +10 returns numbers from 10 to 15. I'm not sure why you want this to be done using numpy but perhaps I've misunderstood your intent.


import numpy as np
>>> 5 + np.random.sample(10) * 5
array([ 7.14292096,  6.84837089,  6.38203972,  8.80365208,  9.06627847,
        5.69871186,  6.37734538,  9.60618347,  9.34319843,  8.63550653])