user3407267
user3407267

Reputation:

Initializing a matrix with random number from given range - python

How to initialize a matrix with random number (say 0 to 0.01)?

           A = numpy.random.rand(2,3)

This gives the result:

          >>A
               array([[ 0.45378345,  0.33203662,  0.42980284],
                      [ 0.2150098 ,  0.39427043,  0.10036063]]) 

But how to specify the range of random numbers ( 0 to 0.01)?

Upvotes: 2

Views: 8381

Answers (1)

ajwood
ajwood

Reputation: 19027

The numbers returned by numpy.random.rand will be between 0 and 1. Knowing that, you can just multiply the result to the given range:

# 0 to 0.001
A = numpy.random.rand(2,3) * 0.01

# 0.75 to 1.5
min = 0.75
max = 1.5
A = ( numpy.random.rand(2,3) * (max - min) ) + min

Or as DSM suggested:

A = numpy.random.uniform(low=0.75, high=1.5, size=(2,3) )

Upvotes: 6

Related Questions