Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate each column of the numpy array with random number from different range

Tags:

python

numpy

How to generate a numpy array such that each column of the array comes from a uniform distribution within different ranges efficiently? The following code uses two for loop which is slow, is there any matrix-style way to generate such array faster? Thanks.

import numpy as np
num = 5
ranges = [[0,1],[4,5]]
a = np.zeros((num, len(ranges)))
for i in range(num):
    for j in range(len(ranges)):
        a[i, j] = np.random.uniform(ranges[j][0], ranges[j][1])
like image 452
tczj Avatar asked Nov 22 '17 15:11

tczj


People also ask

How do I generate a random number between NumPy ranges?

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 you generate a random number between specific ranges in Python?

Use a random. randrange() function to get a random integer number from the given exclusive range by specifying the increment. For example, random. randrange(0, 10, 2) will return any random number between 0 and 20 (like 0, 2, 4, 6, 8).

How do you generate an array of random numbers using NumPy in Python?

To create a matrix of random integers in Python, randint() function of the numpy module is used. This function is used for random sampling i.e. all the numbers generated will be at random and cannot be predicted at hand. Parameters : low : [int] Lowest (signed) integer to be drawn from the distribution.

How do I select a random number from a NumPy array?

random. choice() function is used to get random elements from a NumPy array. It is a built-in function in the NumPy package of python.


1 Answers

What you can do is produce all random numbers in the interval [0, 1) first and then scale and shift them accordingly:

import numpy as np
num = 5
ranges = np.asarray([[0,1],[4,5]])
starts = ranges[:, 0]
widths = ranges[:, 1]-ranges[:, 0]
a = starts + widths*np.random.random(size=(num, widths.shape[0]))

So basically, you create an array of the right size via np.random.random(size=(num, widths.shape[0])) with random number between 0 and 1. Then you scale each value by a factor corresponding to the width of the interval that you actually want to sample. Finally, you shift them by starts to account for the different starting values of the intervals.

like image 57
jotasi Avatar answered Sep 28 '22 00:09

jotasi