Skip main navigation

Random numbers

In this article we show how to generate NumPy arrays with random numbers.
© CC-BY-NC-SA 4.0 by CSC - IT Center for Science Ltd.

NumPy provides a wide range of functions to generate random numbers in arrays. These functions are available in the numpy.random module.

The random numbers are generated using the same, excellent pseudo-random number generator called Mersenne Twister that is also used in the normal random module. Mersenne Twister has a period of 2^19937-1 and is generally regarded as a very good pseudo-random number generator (for non-cryptographic purposes).

Several functions for constructing random arrays are provided, including:

  • random: uniform random numbers
  • normal: normal distribution
  • choice: random sample from given array
a = numpy.random.random((2,2))

# output:
# [[ 0.02909142 0.90848 ]
# [ 0.9471314 0.31424393]]

b = numpy.random.choice(numpy.arange(4), 10)

# output: [0 1 1 2 1 1 2 0 2 3]

What kind of random numbers do you need in your won work? Can you find them in NumPy?

© CC-BY-NC-SA 4.0 by CSC - IT Center for Science Ltd.
This article is from the free online

Python in High Performance Computing

Created by
FutureLearn - Learning For Life

Our purpose is to transform access to education.

We offer a diverse selection of courses from leading universities and cultural institutions from around the world. These are delivered one step at a time, and are accessible on mobile, tablet and desktop, so you can fit learning around your life.

We believe learning should be an enjoyable, social experience, so our courses offer the opportunity to discuss what you’re learning with others as you go, helping you make fresh discoveries and form new ideas.
You can unlock new opportunities with unlimited access to hundreds of online short courses for a year by subscribing to our Unlimited package. Build your knowledge with top universities and organisations.

Learn more about how FutureLearn is transforming access to education