Let us review algorithm 1.
is a fairly expensive operation. First,
involves multiplication. The killer part is division by
. Division is a bit more expensive than multiplication.
Let's deal with one problem at a time. To avoid division, we can change the comparison as follows:
![]() |
(6.7) | ||
| (6.8) |
This is true because
is a positive quantity.
But, doesn't this still involves two multiplications in
?
In general, the answer is yes. If
is a constant, then we can
roll
into a single constant to get rid of one multiplication.
is a variable, so we cannot roll this into a constant.
However, we can still do some tricks to avoid having to multiply
to
every time. Remember what
represents: it is the
number of steps to perform. This means most of the time,
is incremented or decremented by 1. This is useful, because now
we can use a variable for a scaled
. Whenever we decrement 1 from
, we subtract
from the scaled version. Note that we still
need to multiply when we reset
to an arbitrary number.
How about the computation of
? It certainly appear that we cannot
easily get rid of the multiplication here.
Once again, think of what
represents. This is the frequency of
stepping
. Most of the time, if not all,
is only
incremented or decremented by 1 (in the acceleration logic). This
is a very useful fact because we can now eliminate multiplication.
If we know
, we can compute
as follows:
| (6.9) | |||
| (6.10) | |||
| (6.11) |
See, no multiplications! Using a similar technique, you can also
derive
using no multiplication from
.
Although this optimization can save you a lot of processing time,
you do need to track quite a few more properties in the
structures. As a result, I recommend the use of abstract data types
so that you use a single function to increment/decrement
. This
same function is also responsible to track a separate variable
for
. The same applies to
and its scaled version.
Copyright © 2006-02-15 by Tak Auyeung