Welcome, guest | Sign In | My Account | Store | Cart

This recipe shows some of the many uses of random numbers, using the random function from the random module from Python's standard library. A subsequent recipe or two will show other uses, both of other functions from the module, and for other purposes.

The uses shown in this recipe have to do with using random float values, and scaling them and offsetting them, and also how to get a repeated/predictable series of random numbers.

Python, 36 lines
 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36``` ```from __future__ import print_function # fn_random.py # A program showing various uses of the "random" function # from the "random" module of Python's standard library. # Author: Vasudev Ram - https://vasudevram.github.io # Copyright 2016 Vasudev Ram from random import random from random import getstate, setstate print("Ex. 1. Plain calls to random():") print("Gives 10 random float values in the interval [0, 1).") for i in range(10): print(random()) print() print("Ex. 2. Calls to random() scaled by 10:") print("Gives 10 random float values in the interval [0, 10).") for i in range(10): print(10.0 * random()) print() print("Ex. 3. Calls to random() scaled by 10 and offset by -5:") print("Gives 10 random float values in the interval [-5, 5).") for i in range(10): print(10.0 * random() - 5.0) print() print("Ex. 4. Calls to random() scaled by 20 and offset by 40:") print("Gives 10 random float values in the interval [40, 60).") for i in range(10): print(20.0 * random() + 40.0) ```

I found that some newer programmers have not come across some of the techniques demonstrated here (and in a follow-up recipe or two to be written). So I thought of writing about it.

More details, and sample output, here: Steven D'Aprano 6 years, 9 months ago

The random module contains functions to do these things, which are better (less biased) than messing about with `random.random()` directly. Your examples are better written using `uniform`:

``````random.uniform(0, 10)  # example 2
random.uniform(-5, 5)  # example 3
random.uniform(40, 60)  # example 4
`````` Vasudev Ram (author) 6 years, 9 months ago

Are you sure?

I looked at the definition of the `uniform` function, it seems to be mostly just calling `random`, not doing anything to make the distribution "less biased" as you put it.

Maybe you were thinking of something else? Vasudev Ram (author) 6 years, 8 months ago

So, not substantiating your claims ... ? Created by Vasudev Ram on Wed, 1 Jun 2016 (BSD)