// ************************************************************************** //
//                                                                            //
//    eses                   eses                                             //
//   eses                     eses                                            //
//  eses    eseses  esesese    eses   Embedded Systems Group                  //
//  ese    ese  ese ese         ese                                           //
//  ese    eseseses eseseses    ese   Department of Computer Science          //
//  eses   eses          ese   eses                                           //
//   eses   eseses  eseseses  eses    University of Kaiserslautern            //
//    eses                   eses                                             //
//                                                                            //
// ************************************************************************** //
// This module computes square roots by Heron's iteration, i.e. the Newton    //
// iteration applied to function f(x) = x^2 - a. As seen in the code, the     //
// algorithm simply computes next(x) = (x+(a/x))/2 until the old value of x   //
// is larger than the new one. Note that all computations are done with type  //
// nat, where a fixed point arithmetic is assumed that multiplies all numbers //
// by exp(10,N) with the compile time constant N.                             //
// ************************************************************************** //

macro N = 200;

module SquareRoot(nat ?a,x,event !rdy) {
    nat x_old;
    x = a;
    do {
        next(x_old) = x;
        next(x) = (x+(a/x))/2;
        pause;
    } while(x_old>x);
    emit(rdy);
}
drivenby {
    a = 2*exp(10,N);
    await(rdy);
}