numpy is a very commonly used scientific computing library in Python. It provides many fast and efficient numerical operations and data processing functions. In numpy, we can easily generate random numbers. This article will introduce the method of generating random numbers in numpy and give specific code examples.
The functions that generate random numbers in numpy mainly include the rand() function, randn() function, randint() function, uniform() function, normal() function, etc. under the random module.
The sample code is as follows:
import numpy as np #生成一个具有5个元素的一维数组 arr1 = np.random.rand(5) print(arr1) #生成一个2行3列的二维数组 arr2 = np.random.rand(2, 3) print(arr2)
The sample code is as follows:
import numpy as np #生成一个具有5个元素的一维数组 arr1 = np.random.randn(5) print(arr1) #生成一个2行3列的二维数组 arr2 = np.random.randn(2, 3) print(arr2)
The sample code is as follows:
import numpy as np #生成一个在[0,10)之间的一维整数数组 arr1 = np.random.randint(0, 10, size=5) print(arr1) #生成一个在[0,10)之间2行3列的二维整数数组 arr2 = np.random.randint(0, 10, size=(2, 3)) print(arr2)
The sample code is as follows:
import numpy as np #生成一个在[2,5)之间的一维数组 arr1 = np.random.uniform(2, 5, size=5) print(arr1) #生成一个在[2,5)之间2行3列的二维数组 arr2 = np.random.uniform(2, 5, size=(2, 3)) print(arr2)
The sample code is as follows:
import numpy as np #生成均值为2,标准差为0.5的一维数组 arr1 = np.random.normal(2, 0.5, size=5) print(arr1) #生成均值为2,标准差为0.5的2行3列的二维数组 arr2 = np.random.normal(2, 0.5, size=(2, 3)) print(arr2)
Through the above code examples, we can see that numpy provides a wealth of random number generation functions, which can meet various needs for generating random numbers, and Very easy to use. In practical applications, we can choose an appropriate random number generation function according to specific needs, and generate random numbers that meet our needs by specifying parameters.
The above is the detailed content of How to generate random numbers using numpy. For more information, please follow other related articles on the PHP Chinese website!