2

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)?

1 Answer 1

6

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) )
Sign up to request clarification or add additional context in comments.

1 Comment

np.random.uniform might be simpler, esp. when the lower limit isn't zero.

Your Answer

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