Download presentation
Presentation is loading. Please wait.
Published bySharleen Butler Modified over 6 years ago
1
Random Numbers In today’s lesson we will look at:
why we might want a random number whether they really are random how to create and scale random numbers in Python
2
Why Random Numbers? Random things are unpredictable
You might want to add randomness to a program so that it doesn’t behave in the same way every time. Some people think that randomness makes things seem more “real” or “human” – e.g. making things wobbly. You might want to simulate or model an actual random event – e.g. a dice throw
3
Examples A tree drawn in Scratch using recursion
The same program with added randomness
4
Can a Computer Do That? Random numbers are unpredictable, but computers always follow rules A computer can’t really create random numbers – it uses rules to create pseudo-random numbers The computer might use all sorts of variables that change – e.g. the time – to help it create numbers that appear to be random.
5
Programming Randomness
Most programming languages (and also spreadsheets and other applications) only give you a number from 0 to 1. In BASIC, for example, the following program would print a random number: X = RND(1) PRINT X Excel is very similar. Python doesn’t work like that, though.
6
Python Example The first thing you need to do is import the random library using the following code: from random import randint You can then use the randint() function, e.g. to simulate the roll of a die you could use: die = randint(1,6) That would give you a random integer from 1 to 6
7
Random Things What happens if you want a random thing that isn’t a number, for example a random day, or a random person from your class? You can number the days, people, etc., and put their names into a list or tuple. You can then produce a random number and use that as the index to look up the name.
8
Example? To give a random day of the week: from random import randint
day = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") for i in range(10): print(day[randint(0,6)])
9
Distribution All of the examples so far produce random numbers with a linear distribution – i.e. they should be spread evenly throughout the chosen range. What about if you wanted it to be more likely that you’d get a small number (or a large one)? Think about square numbers – 1, 2, 4, 9, 16, 25, 36, 49, 64, 81, 100, etc. – how are they spaced? You can change the distribution of random numbers by raising them to a power.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.