Algebraic simplification 2 Comments
I was translating Pascal to C as usual for Missions when I came across the code fragment for computing the time bonus earned on victory given the current game time:
x := BSR(gCycle, 4) + 1; x := round(50000 / x) * 10;
Now, I could have translated that to C as timeBonus = (50000 / ((cycle >> 4) + 1)) * 10, but I decided to get clever. Uh oh. I applied algebra to simplify the equation.
To translate it algebraically, I had to convert it to a purely mathematical equation. The right shift operator >> isn’t algebraic, but given the identity that x >> y = x / 2y, a right shift of four bits is an integer divide by 16. “cycle” is just a variable, so call it x, giving us the algebraic equation (50000 / ((x / 16) + 1)) * 10, or:
Next, multiply 10 (as 10 / 1) into the equation:
Using the equality a/b + c/d = ad + bc / bd, rewrite (x / 16) + 1:
Rewrite using the equality a / (b / c) = a * (c / b):
Leaving us with two operations (add and divide) where originally there were four (shift, add, divide, multiply). Isn’t math cool?
All equation images generated by Apple’s Grapher program. Nice little feature that thing has, copy equation as TIFF.
March 17, 2010 at 6:35 pm