Lesson goal: Rescaling a variable

Previous: Changing a variable in one line | Home | Next: Drawing lines with the mouse

In a past lesson, you learned how a single line can alter a given variable. In this lesson, we'll look at how a single line can rescale a result. Here's we'll look at the math.random() statement, that returns a random number between 0 and 1.

On first look, a random number between $0$ and $1$ may not be so useful. It would seem that math.random(low,high) is better, as covered in this lesson, because we can choose the range of the random number that the computer selects. But the problem with math.random(low,high) is that it only returns integers. What if we wanted a fractional result? For example, if we wanted a random number between 1 and 10, isn't 2.56 allowed? This is where rescaling math.random() will help.

What we would like to do is transform the numbers from $0..1$ to numbers between $A..B$, where $A$ and $B$ are minimum and maximum numbers of our choosing. We can do it like this: If $r$ is a random number between $0$ and $1$, then a random number between $A$ and $B$ would be $n=(B-A)r+A$.

Now you try. Rescaling math.random() to give a fractional random number between say, 50 and 125.

Type your code here:


See your results here: