numpy2
中文版:NumPy 复习 2
some examples for Numpy 2
- always import the package first!
import numpy as np- if you want, you can choose the random seed first (then everytime the generated random numbers will be the same)
np.random.seed(0)- create variables (array) use rand functions in numpy
# np.random.rand()
# Generates random floats in the range [0, 1).
# Generate 1 random float
x = np.random.rand()
print(x)
# Generate a 2×3 matrix of random floats
x = np.random.rand(2, 3)
print(x)# np.random.randint()
# Generates random integers in a given range.
# Generate one integer from 0 to 9
x = np.random.randint(0, 10)
print(x)
# Generate a 3×2 matrix of integers from 5 to 15
x = np.random.randint(5, 16, size=(3, 2))
print(x)# np.random.choice()
# Randomly picks elements from a given list or array.
# Randomly pick one element from the list
x = np.random.choice([10, 20, 30, 40])
print(x)
# Randomly pick 3 elements (with replacement)
x = np.random.choice([1, 2, 3, 4], size=3)
print(x)# np.zeros(shape)
# Create a 1D array of zeros, length = 5
zeros_1d = np.zeros(5)
print(zeros_1d) # Output: [0. 0. 0. 0. 0.]
# Create a 2×3 array filled with zeros
zeros_2d = np.zeros((2, 3))
print(zeros_2d)# np.ones(shape)
# Create a 1D array of ones, length = 4
ones_1d = np.ones(4)
print(ones_1d) # Output: [1. 1. 1. 1.]
# Create a 3×2 array filled with ones
ones_2d = np.ones((3, 2))
print(ones_2d)fix the errors
# Generate a 2D matrix of random floats
x = np.random.rand(2)
print(x)# Generate a 1D matrix of random floats
x = np.random.rannd(2)
print(x)# Generate a 2×3 matrix of random floats
x = np.random.rand(3, 2)
print(x)# Generate one integer from 0 to 9
x = np.random.randint(0, 9) #wrong!
print(x)# Generate a 3×2 matrix of integers from 1 to 15
x = np.random.randint(5, 15, size=(2, 2))
print(x)