← Back to NumPy Course | Chapter 2: Creating Arrays | Lesson 6 of 7

np.random basics

NumPy can generate random numbers, which is handy for sample data and simulations.

In this page:

  1. np.random basics
Syntax
python
rng = np.random.default_rng(seed)
rng.random(size)
rng.integers(low, high, size)
rng.normal(loc, scale, size)

np.random basics

The modern way is np.random.default_rng(seed), which returns a Generator with methods such as random, integers and normal. Setting a seed makes results reproducible. Legacy functions like np.random.rand still work and are covered later.

Note: Always seed when you want the same numbers every run, such as in tutorials and tests.

Example: np.random basics

python
import numpy as np

rng = np.random.default_rng(42)
print(rng.random(3).round(3))
print(rng.integers(1, 10, size=5))

# Output:
# [0.774 0.439 0.859]
# [1 7 2 1 5]
Related Topics
Common Mistakes
  1. Forgetting to seed and getting different output each time
  2. Mixing legacy and Generator APIs
  3. Expecting integers() upper bound to be inclusive
Chapter Summary
  • default_rng creates a Generator
  • Seed for reproducibility
  • random gives floats in 0 to 1
  • integers excludes the high value
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.