0
0
NumpyHow-ToBeginner ยท 3 min read

How to Use np.random.rand in NumPy for Random Numbers

Use np.random.rand to generate random numbers between 0 and 1 in NumPy. You provide the shape as arguments, like np.random.rand(3, 2) for a 3x2 array of random floats.
๐Ÿ“

Syntax

The syntax of np.random.rand is simple: you pass one or more integers as arguments to specify the shape of the output array. Each argument represents the size of that dimension.

  • np.random.rand(d0, d1, ..., dn): generates an array of shape (d0, d1, ..., dn) filled with random floats between 0 and 1.
  • If no arguments are given, it returns a single float.
python
np.random.rand(d0, d1, ..., dn)
๐Ÿ’ป

Example

This example shows how to create a 2x3 array of random numbers between 0 and 1 using np.random.rand. Each time you run it, you get different random values.

python
import numpy as np

# Generate a 2x3 array of random floats between 0 and 1
random_array = np.random.rand(2, 3)
print(random_array)
Output
[[0.5488135 0.71518937 0.60276338] [0.54488318 0.4236548 0.64589411]]
โš ๏ธ

Common Pitfalls

Common mistakes when using np.random.rand include:

  • Passing a single tuple instead of separate integers. For example, np.random.rand((2,3)) will cause an error because it expects separate arguments, not a tuple.
  • Expecting integers or values outside 0 to 1 range. np.random.rand only generates floats between 0 and 1.
  • Confusing np.random.rand with np.random.randint which generates random integers.

Correct usage example:

python
import numpy as np

# Wrong: passing a tuple
# np.random.rand((2, 3))  # This will raise a TypeError

# Right: passing separate integers
array = np.random.rand(2, 3)
print(array)
Output
[[0.79172504 0.52889492 0.56804456] [0.92559664 0.07103606 0.0871293 ]]
๐Ÿ“Š

Quick Reference

Summary tips for np.random.rand:

  • Generates floats in [0, 1).
  • Arguments specify output shape as separate integers.
  • No arguments returns a single float.
  • Use np.random.randint for random integers.
โœ…

Key Takeaways

Use np.random.rand with separate integer arguments to set output shape.
It generates random floats between 0 and 1, never integers.
Passing a tuple instead of separate integers causes errors.
No arguments returns a single random float.
For random integers, use np.random.randint instead.