80 likes | 242 Views
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. Why Random Numbers?. Random things are unpredictable
E N D
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
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
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.
Programming Randomness • 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.
Scaling the Number • 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
Example? • 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
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 an array. • You can then produce a random number and use that as the array index to look up the name.
Example? • 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) + 1print day$(day_no)