NumPy — Random
Random sampling
import numpy as np
# Random float [0, 1)
print(np.random.rand(3, 3))
# Random int
print(np.random.randint(0, 10, (3, 3)))
# Random normal
print(np.random.randn(3, 3))
Seed
np.random.seed(42)
arr = np.random.rand(5)
print(arr)
Random state
rng = np.random.default_rng(42)
arr = rng.random(5)
print(arr)
Distributions
# Uniform
print(np.random.uniform(0, 1, 5))
# Normal
print(np.random.normal(0, 1, 5))
# Poisson
print(np.random.poisson(5, 5))
# Exponential
print(np.random.exponential(1, 5))
Choice
arr = np.array([1, 2, 3, 4, 5])
print(np.random.choice(arr, 3, replace=False))
Shuffle
arr = np.array([1, 2, 3, 4, 5])
np.random.shuffle(arr)
print(arr)
Mini Practice
- Generate random numbers
- Set seed for reproducibility
- Use different distributions
- Practice choice and shuffle
Up Next
Continue with File I/O - Reading and writing files.
Related Topics
Frequently Asked Questions about Random
What is Random in NumPy?
Random is a fundamental concept in NumPy. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Random?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Random.
Why is Random important in NumPy?
Random is essential for NumPy development. Understanding this concept will help you write better code and solve real-world problems more effectively.