Home > Software engineering >  Random number matrix within a specified range in Python
Random number matrix within a specified range in Python

Time:04-27

I would like to generate a random number matrix within a specified range, say (0,1).

import numpy as np
A=np.random.random((3, 3))
print("A =",[A])

CodePudding user response:

numpy.random.uniform can receive low, high and size parameters

Range 0-1 is the default

A = np.random.uniform(size=(3, 3))
print("A =", [A])

Output

A = [array([[0.76679099, 0.57459256, 0.07952816],
            [0.02736909, 0.05905416, 0.09909474],
            [0.08690106, 0.81983883, 0.18740471]])]

If you want another range specify it with parameters

A = np.random.uniform(0.2, 0.3, (3, 3))
print("A =", [A]) 

Output

A = [array([[0.20548205, 0.25373507, 0.28957419],
            [0.20496673, 0.27004844, 0.28633947],
            [0.22325187, 0.26327935, 0.24548129]])]

CodePudding user response:

you will be use it generate range [0, 1)

np.random.rand(d0, d1, ..., dn)

Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1).

https://numpy.org/doc/stable/reference/random/generated/numpy.random.rand.html

CodePudding user response:

You can use Numpy's built-in rand method, which generates a matrix with random numbers with a uniform distribution over [0, 1).

A = np.random.rand(3, 3)
  • Related