0

I have ranges, where each tuple represents the range of a random number. e.g:

ranges = [(-1,100), (0,1), (50, 5000)]

Now, I want to create a numpy array where each element of array is randomly generated from the corresponding tuple of ranges.

Pseudo code:

rand_array = numpy.array[randomly generate element1 from (-1,100), randomly generate element2 from (0,1), randomly generate element3 from (50,500)]

Of course, naive way to do this is:

rand_array = [random.uniform(coord[0], coord[1]) for coord in ranges]

But I want to do it in numpy way, as my whole code accepts numpy array data-types. Another solution can be to convert naively generated rand_array to numpy array. But I think it is not efficient. Is there a numpy way of doing this?

1 Answer 1

4

Most random functions accept array parameters. So you can do

np.random.uniform(*np.transpose(ranges))

The usual broadcasting rules apply, for example, to get 10 triplets

np.random.uniform(*np.transpose(ranges),(10,3))
Sign up to request clarification or add additional context in comments.

1 Comment

thanks. How to generate x number of elements in this way? is there a way to do this like this: np.random.uniform(x, *np.transpose(ranges)) (where x is an integer specifying numebr of elements or rows of numpy array). Sorry, I forgot to include that in question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.