Search

The Secrets Of Random Numbers In Python Part 1

python random numbers
 

When people think of random numbers, they think of something disorganized and that cannot be predicted. That is what I thought until I entered the world of random numbers using python. You see, random numbers do not just run arbitrarily. The name is deceptive. They are based on what are called seeds. A seed can either be provided by the programmer, and if one is not provided, python uses the system clock or what is supplied by the operating system.

If you decide to set the random number generator rather than allow the program to initialize it on its own, you call the random.seed function, supplying it with a seed that you desire. The seed has to be an int. This could be done using the code:

As you can see from running the above code where we gave the random function the same seed, the same output was produced consecutively. That is why the random function is deceptive. Why it is really random is because since the programmer most times does not provide a seed but allows it to self-generate, the random number becomes really random.

By the way, the disclaimer from the makers of the python programming language is that the functions in the random module should not be used in cryptography.

Now let’s take a ride on some of the functions included in the random module.

The functions are divided into functions that manipulate integers, sequences, and real-valued distributions. We will concentrate on the first two in this article.

What are the functions that manipulate integers.

The two functions in the random module that manipulate integers are random.randint and random.randrange. They both do the same thing. They return an integer based on a given range. The differences between them is that in random.randint the second positional argument is included in the range of numbers to be considered, while in random.randrange the range to consider stops just before the second positional argument. The syntax for both of them is random.randint(a, b) and random.randrange(start, stop[, step]). For random.randrange the stop is not included in the range that is to be considered, while in random.randint the last positional argument, b, is considered in the range to be considered. Also, note that you could step through random.randrange using the step argument. For example, you could leave out some numbers in a range using step, just as you can do using the in-built range function.

Overall, both of them serves the same function: give a random integer from a given range and conditions.

If you run the code below, you will be sure to get a random integer between 1 and 20 inclusive.

What are the functions that manipulate sequences.

The functions for manipulating sequences are four in number and they sometimes overlap. I will describe each of them and give code you can run.

random.choice(sequence):

This function returns a random element from sequence provided sequence has items in it otherwise it will raise an IndexError. I think this is simple enough. Now, the code.

Each time you run the code above, it will give you a chosen fruit. There are repeats too. So, don’t be surprised because the list of fruits is not exhaustive.

random.choices(population, weights=None, *, cum_weights=None, k=1):

This function returns a list of size k (default is 1, note) from the population which could be a sequence or a range. If you do not want to apply any probability to the items that would be returned in the list, then you would leave weights and cum_weights keyword arguments alone. But if you want to give some weight or assign probabilities to what can be chosen at random, you have to provide value for weights or cumulative weight, cum_weights. Using the list from above, let us give higher probability to apple and orange using the keyword argument, weights=[5,5,5,15,15]. I will also tell the code to chose just two items from the list of fruits at random.

If you run the code, you will see that you will have a high probability of having orange and apple in the returned list rather than the other fruits. One point to note is that weights cannot be negative.

random.shuffle(x[, random]):

This function takes as argument a sequence, x, and shuffles the items in place. You can provide an optional random function that could be used to shuffle the items. I think this is well explained using code. I will provide code that does not use the random function and one that does.

This code does not use the random function.

Each time you run it, it randomly rearranges the items in the list.

Now this one uses a random function. I want you to run it more than one time and notice the arrangement of the items.

Did you notice that the rand_function acted as a seed to the random.shuffle function? Each time it runs, it returns the list of items in the same sequence. Very cool! You can play with it. Note that the random function can be any function that returns a floating point number between 0.0 and 1.0. I used 0.09.

Now for the last function that manipulates sequences.

random.sample(population, k):

This function is used for random sampling without replacement. It returns a list of size k from the population. It is similar to the choices function but without the weights and without replacement. In random.choices, the returned list can have repeated items but not in random.sample. Now for some code.

Run the above code repeatedly and see. The sample size, k, should not be larger than the population size otherwise python will raise a ValueError.

You can use this function to generate a random list of integers from a very large sample size using the range function as the population argument using code like this: random.sample(range(1000000), 100). Very cool and very efficient.

So, that is the secret to the random function. Now that you have learned what it is and how to use it, why don’t we play with it a little.

Tomorrow, I am going to post a little game that uses the random function. So, make sure to watch out for the game.

Happy pythoning.

No comments:

Post a Comment

Your comments here!

Matched content