/* This may look like a -*- C -*- code, but it's only similiar.
 *
 *    Calc: A Programmable Calculator for GTK+
 *    Copyright (C) 2000  David Hanak (dhanak@inf.bme.hu)
 *
 *    This file can be distributed under GNU GPL.  See file COPYING.
 *
 *    $Id: newton,v 2.0 2000/02/16 16:47:40 david Exp $
 * 
 * This is an example for Calc.
 */

/* Square root calculation with Newton iteration.
 *   num:  the number to get root of
 *   prec: precision of calculation
 */
fun n_sqrt(num, prec) =
{
  var (root, prev);

  root = num/2;
  do {
    prev = root;
    root = (num/root + root) / 2
  } while (abs(prev - root) > prec);
  root
};

/* Root calculation of any function by the Newton method.
 *   f:    a function of 'x', in string representation (e.g., "sin(x)")
 *   fd:   the first derivative of 'f', also in string (e.g., "cos(x)")
 *   prec: precision of calculation
 *   x:    initial value of 'x', should be close to the real root
 */
fun n_root(f, fd, prec, x) =
{
  var (x0, step);

  step = 0;
  do {
    x0 = x;
    x -= eval(f) / eval(fd)
  } while (abs(x0 - x) > e);
  x
}
