next up previous contents
Next: Noise Related Problems and Up: Stepper Motor Control Previous: Steering   Contents

Efficient Implementation

If you try to implement the program following the pseudocode, you will end up with a program that works, but not necessarily efficiently.

It is easy to determine whether two numbers have the same sign. The hint is to use the MSB (most significant bit) as the sign bit, then use bit-wise operations to help you determine whether two numbers have the same sign bit.

Multiplying a number by a sign is an expensive method to change the sign of a number. For example, recall the following code:


\begin{algorithmic}
\IF{$sign(d) \times v < v_{max}$}
\STATE set $a = a_{max} \times sign(d)$
\ELSE
\STATE set $a = 0$
\ENDIF
\end{algorithmic}

This code can be implemented by


\begin{algorithmic}
\IF{$d < 0$ and $v > -v_{max}$}
\STATE set $a = -a_{max}$...
...
\STATE set $a = a_{max}$
\ELSE
\STATE set $a = 0$
\ENDIF
\end{algorithmic}

The new implementation is a little less general and therefore longer. However, there is no multiplication involved. Negating constants such as $v_{max}$ and $a_{max}$ is easy and is done at compile time. Determining whether a number is negative or not is also easy in hardware (sign bit).


Tak Auyeung 2003-09-29