3.1: Updating Variables
- Page ID
- 84536
In Exercise 2.2 of Section 2.9, I asked you to write a program that models a bike-share system with bikes moving between two stations. Each day 5 percent of the bikes in Boston are dropped off in Cambridge, and 3 percent of the bikes in Cambridge get dropped off in Boston.
To update the state of the system, you might have been tempted to write something like
b = b - 0.05*b + 0.03*c
c = c + 0.05*b - 0.03*c
But that would be wrong, so very wrong. Why? The problem is that the first line changes the value of b
, so when the second line runs, it gets the old value of c
and the new value of b
. As a result, the change in b
is not always the same as the change in c
, which violates the Principle of Conservation of Bikes!
One solution is to use temporary variables like b_new
and c_new
:
b_new = b - 0.05*b + 0.03*c
c_new = c + 0.05*b - 0.03*c
b = b_new
c = c_new
This has the effect of updating the variables simultaneously; that is, it reads both old values before writing either new value.
The following is an alternative solution that has the added advantage of simplifying the computation:
b_to_c = 0.05*b - 0.03*c
b = b - b_to_c
c = c + b_to_c
It’s easy to look at this code and confirm that it obeys Conservation of Bikes. Even if the value of b_to_c
is wrong, at least the total number of bikes is right. And that brings us to the Fifth Theorem of Debugging:
The best way to avoid a bug is to make it impossible.
In this case, removing redundancy also eliminates the opportunity for a bug.