Fundamentals 8 min read

Master Python’s random Module and NumPy: 7 Ways to Generate Random Numbers

Learn how to use Python’s built‑in random module and NumPy’s random functions to generate various types of random numbers—including floats, integers, ranges, selections, shuffling, and sampling—while understanding seeds, pseudo‑randomness, and practical code examples for each method.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python’s random Module and NumPy: 7 Ways to Generate Random Numbers

Random numbers are widely used, such as adding salt to passwords or in Monte Carlo simulations.

Python’s built‑in random module provides methods for generating random numbers; you need to import it first. import random Below are several common functions in the random module.

1. random.random()

Generates a floating‑point number in the interval [0.0, 1.0). The value can be 0 but never 1.

print("random:", random.random())

2. random.randint(a, b)

Returns an integer N such that a ≤ N ≤ b. For a half‑open interval [a, b) use random.randrange().

print("randint:", random.randint(6, 8))

3. random.randrange(start, stop, step)

Returns a randomly selected element from the range(start, stop, step), i.e., start ≤ N < stop.

print("randrange:", random.randrange(20, 100, 5))

4. random.uniform(a, b)

Generates a floating‑point number N such that a ≤ N ≤ b.

print("uniform:", random.uniform(5, 10))

5. random.choice(seq)

Randomly selects an element from a non‑empty sequence (list, tuple, string, etc.). Raises IndexError if the sequence is empty.

print("choice:", random.choice("www.yuanxiao.net"))

6. random.shuffle(seq)

Shuffles the sequence in place. To keep the original sequence, copy it first (e.g., using the copy module).

num = [1, 2, 3, 4, 5]
random.shuffle(num)
print("shuffle:", num)

7. random.sample(seq, n)

Returns a list of n unique elements chosen from the sequence.

num = [1, 2, 3, 4, 5]
print("sample:", random.sample(num, 3))

The numbers produced by random are pseudo‑random; they are generated by deterministic algorithms seeded by a value. Using the same seed reproduces the same sequence, while omitting the seed defaults to the current system time.

random.seed(2)
print("random:", random.random())
random.seed(3)
print("random:", random.random())

NumPy also offers a random submodule for generating multi‑dimensional arrays of random numbers.

import numpy as np

1. numpy.random.rand(d0, d1, …, dn)

Generates an array of shape (d0, d1, …, dn) with values drawn from a uniform distribution over [0, 1).

print("np.random.rand:", np.random.rand(4, 2))

2. numpy.random.randn(d0, d1, …, dn)

Returns samples from the standard normal distribution (mean 0, standard deviation 1).

print("np.random.randn:", np.random.randn())
print("np.random.randn:", np.random.randn(2, 4))

3. numpy.random.randint(low, high=None, size=None, dtype='l')

Returns random integers from the interval [low, high) (low inclusive, high exclusive). If high is omitted, the range is [0, low).

print("np.random.randint:", np.random.randint(1, size=5))
print("np.random.randint:", np.random.randint(1, 5))
print("np.random.randint:", np.random.randint(-5, 5, size=(2,2)))

4. numpy.random.seed()

Sets the seed for NumPy’s random generator, making the generated data reproducible. Without setting a seed, each run produces different numbers.

Source: https://juejin.im/post/5cefccb0e51d455d850d3a85
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonTutorialNumPyrandompseudo-randomseed
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.