Labs ICT
Pro Login

Random Arrays

Generating random data for testing and simulations.

Random Arrays

Random numbers are everywhere in computing - simulations, testing, machine learning. Think of it like rolling dice, but you can roll a million dice at once.

Uniform Distribution

np.random.rand() creates random floats between 0 and 1.


import numpy as np

random_1d = np.random.rand(5)
random_2d = np.random.rand(3, 4)

print(f"1D Random: {random_1d}")
print(f"2D Random:\n{random_2d}")
    

Each run gives different numbers. That's because they're random! But sometimes you want reproducible results.

Setting a Seed

Use np.random.seed() to make random numbers reproducible. Same seed = same numbers.


import numpy as np

np.random.seed(42)
first_run = np.random.rand(3)

np.random.seed(42)
second_run = np.random.rand(3)

print(f"First: {first_run}")
print(f"Second: {second_run}")
print(f"Same? {np.array_equal(first_run, second_run)}")
    

Trust me, setting seeds is crucial for debugging and sharing results. I definitely forgot this many times and got different results each run.

Random Integers

np.random.randint() gives you random integers within a range.


import numpy as np

dice_rolls = np.random.randint(1, 7, size=10)
random_ints = np.random.randint(0, 100, size=(3, 3))

print(f"10 dice rolls: {dice_rolls}")
print(f"3x3 random ints:\n{random_ints}")
    

Normal Distribution

np.random.randn() gives numbers from a standard normal distribution (mean 0, std 1).


import numpy as np

normal_data = np.random.randn(5)
print(f"Normal distribution: {normal_data}")
print(f"Mean: {np.mean(normal_data):.3f}")
    

One thing that confused me at first was the difference between rand and randn. Rand gives uniform (0-1), randn gives normal distribution.

Try it Yourself →

Key Takeaways

  • np.random.rand() creates uniform random floats [0, 1)
  • np.random.randint() creates random integers in a range
  • np.random.randn() creates normal distribution values
  • Use np.random.seed() for reproducible results