Simple way to create matrix of random numbers

前端 未结 13 1663
灰色年华
灰色年华 2020-12-12 21:20

I am trying to create a matrix of random numbers, but my solution is too long and looks ugly

random_matrix = [[random.random() for e in range(2)] for e in ra         


        
相关标签:
13条回答
  • 2020-12-12 22:23

    For creating an array of random numbers NumPy provides array creation using:

    1. Real numbers

    2. Integers

    For creating array using random Real numbers: there are 2 options

    1. random.rand (for uniform distribution of the generated random numbers )
    2. random.randn (for normal distribution of the generated random numbers )

    random.rand

    import numpy as np 
    arr = np.random.rand(row_size, column_size) 
    

    random.randn

    import numpy as np 
    arr = np.random.randn(row_size, column_size) 
    

    For creating array using random Integers:

    import numpy as np
    numpy.random.randint(low, high=None, size=None, dtype='l')
    

    where

    • low = Lowest (signed) integer to be drawn from the distribution
    • high(optional)= If provided, one above the largest (signed) integer to be drawn from the distribution
    • size(optional) = Output shape i.e. if the given shape is, e.g., (m, n, k), then m * n * k samples are drawn
    • dtype(optional) = Desired dtype of the result.

    eg:

    The given example will produce an array of random integers between 0 and 4, its size will be 5*5 and have 25 integers

    arr2 = np.random.randint(0,5,size = (5,5))
    

    in order to create 5 by 5 matrix, it should be modified to

    arr2 = np.random.randint(0,5,size = (5,5)), change the multiplication symbol* to a comma ,#

    [[2 1 1 0 1][3 2 1 4 3][2 3 0 3 3][1 3 1 0 0][4 1 2 0 1]]

    eg2:

    The given example will produce an array of random integers between 0 and 1, its size will be 1*10 and will have 10 integers

    arr3= np.random.randint(2, size = 10)
    

    [0 0 0 0 1 1 0 0 1 1]

    0 讨论(0)
提交回复
热议问题