Simple way to create matrix of random numbers

前端 未结 13 1666
灰色年华
灰色年华 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:20

    numpy.random.rand(row, column) generates random numbers between 0 and 1, according to the specified (m,n) parameters given. So use it to create a (m,n) matrix and multiply the matrix for the range limit and sum it with the high limit.

    Analyzing: If zero is generated just the low limit will be held, but if one is generated just the high limit will be held. In order words, generating the limits using rand numpy you can generate the extreme desired numbers.

    import numpy as np
    
    high = 10
    low = 5
    m,n = 2,2
    
    a = (high - low)*np.random.rand(m,n) + low
    

    Output:

    a = array([[5.91580065, 8.1117106 ],
              [6.30986984, 5.720437  ]])
    

提交回复
热议问题