next up previous contents
Next: Analysis Up: Coding an algorithm in Previous: Signed Binary Division by

Signed Binary Average

The implementation of the signed binary average algorithm is also extremely simple once we have the algorithm description. In section 4.3.1, we describe the algorithm as follows:



$\begin{array}
{lrcl}
\lefteqn{\mathrm{average}(x,y) \ = \ \mathrm{average'}(x,y...
 ... 2)\ -1 & \qquad \textrm{if }\ (-6 \leq d<-2)\end{array} \right.\ \end{array}$



The sign function is defined as follows:



$\begin{array}
{l}\mathrm{sign}(x) \ = \ \left\{\begin{array}
{rl}
-1&\qquad \te...
 ...xtrm{if }\ (x=0)\ 1&\qquad \textrm{if }\ (x\gt)\end{array} \right. \end{array}$



This is implemented in Haskell as follows.

-- sbAv : Signed binary stream average operation
sbAv :: SBinStream -> SBinStream -> SBinStream
sbAv x y = sbAv' x y 0 

-- sbAv' : Auxiliary function for sbAv
sbAv' :: SBinStream -> SBinStream -> Int -> SBinStream
sbAv' (a0:x) (b0:y) c = if (d' `mod` 2 == 0) then
                           ((signum d'):(sbAv' x y 0))
                        else sbAv'' x y d'
        where d' = (a0 + b0 + 2*c)


-- sbAv'' : Auxiliary function for sbAv
sbAv'' :: SBinStream -> SBinStream -> Int -> SBinStream
sbAv'' (a1:x') (b1:y') d' = (e : sbAv' (a1:x') (b1:y') c')
        where {d = (2*d' + a1 + b1);
               e = if (d >  2) then  1 else 
                   if (d < -2) then -1 else 0;
               c' = d' - (2*e)}



Martin Escardo
5/11/2000