90 likes | 225 Vues
This article explores the versatile function `rand()` for generating random numbers within a specified range. It covers the syntax and usage, including how to create matrices of random numbers and manipulate these values through basic algebraic operations. The piece provides examples of applications, such as thermometer programming and rocket control software, to illustrate practical uses of random numbers in programming. Finally, we discuss how to generate a float in the desired range using algebraic expressions.
E N D
Generating Random Numbers • Generating random numbers • rand() is another one of those versatile functions x=rand; x=rand(); %some keep the () to remind themselves it is a function-call vs. a variable name. x=rand(1); %avoid, it’s overdoing it… x=rand(2); %a 2-rows by 2-columns matrix x=rand(2,5); %a 2-rows by 5-columns matrix
rand() and a little bit of algebra: +- • What happens to a number k between 0 and 1 if it is added to another number? For example: What can we say about: 2+k ? What can we say about: k-4 ? >> The interval shifts left/right. k 1 0 k 0 2 1 3
rand() and a little bit of algebra: */ • What happens to a number k between 0 and 1 if it is multiplied by another number? For example: What can we say about: 5*k ? What can we say about: k/2 ? >> The interval grows/shrinks. k 0 1 k 0 5
End of algebra • So.. Using a combination of arithmetic operators, how would you generate these values (both excluded): k1 = rand_______________________; k2 = rand_______________________; k1 k2 15 -5.5 20 5.5
Conclusion • To generate 1 float in the interval : ]a,b[ k = rand*(b-a)+a; This is not a formula worth remembering.. Just remember algebra!
Example1 Thermometer A new thermometer is being built. In addition to showing the temperature, the manufacturer also wants to indicate a warning if the temperature is above or equal to 104 degrees Fahrenheit. You are being paid ($$$) to develop the program that will eventually be within the thermometer. It’s been a year, and still no thermometer.. How long are you going to wait???
Example2 Rockets 0/1’s? • How about rockets??? How does software get written? Do we waste a rocket each time? • During launch, so many sensors give back information!!! • A couple of them are…. • Doors locked? True/False • Oxygen flowing properly? True/False • Fuel being delivered to engine? True/False
Wrapping up • Vocabulary • Function call • Arguments • Collecting • Return-values • Versatile • New notions • Generating random numbers • Generating 1 random float value • Manipulating it to desire random range wanted • Generating a zero/one to simulate false/true • Examples • Temperature: rand() • Rocket: rand() and ceil()!!