Presentation on theme: "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."— Presentation transcript:
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 Just Basic
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 Why Random Numbers?
Examples A tree drawn in Scratch using recursion The same program with added randomness
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. Can a Computer Do That?
Most programming languages (and also spreadsheets and other applications) only give you a number from 0 to 1. In Just Basic, the following program would print a random number: X = RND(1) PRINT X Most versions of BASIC, however, don’t require the 1. Programming Randomness
It’s unlikely that you want a number from 0-1 You can scale the number into the right range using arithmetic, e.g. for a whole number: –multiply by the number of possible values that you’d like –round down using int() to give a whole number –add the lowest number you’re expecting Scaling the Number
For example, to simulate a dice roll: –multiply by the number of possible values that you’d like = 6 –round down using int() to give a whole number –add the lowest number = 1 So the result would be: X = INT(RND(1) * 6) + 1 Example?
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 an array. You can then produce a random number and use that as the array index to look up the name. Random Things
To give a random day of the week: Dim day$(7) day$(1) = “Sunday” day$(2) = “Monday” day$(3) = “Tuesday” day$(4) = “Wednesday” day$(5) = “Thursday” day$(6) = “Friday” day$(7) = “Saturday” day_no = INT(RND(1) * 7) + 1 print day$(day_no) Example?
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. Distribution