home *** CD-ROM | disk | FTP | other *** search
/ Big Green CD 8 / BGCD_8_Dev.iso / NEXTSTEP / UNIX / Educational / R-0.49-MI / R-0.49-I / demos / dynload / zero.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-11-24  |  936 b   |  50 lines

  1. #include <math.h>
  2.  
  3. static void *func;
  4.  
  5. static double zfun(double z)
  6. {
  7.     void *args[1], *values[1];
  8.     double zz[1], *result;
  9.     char *mode[1]; long length[1];
  10.  
  11.     mode[0] = "double"; length[0] = 1;
  12.     args[0] = (void*)(zz); zz[0] = z;
  13.  
  14.     call_S(func, 1L, args, mode, length, 0L, 1L, values);
  15.  
  16.     result = (double*)values[0];
  17.     return result[0];
  18. }
  19.  
  20. static double zero_approx(double(*f)(), double x0, double x1, double tol)
  21. {
  22.     double f0, f1, fc, xc;
  23.     f0 = zfun(x0);
  24.     f1 = zfun(x1);
  25.     if(f0 == 0.0) return x0;
  26.     if(f1 == 0.0) return x1;
  27.     if(f0*f1 > 0.0) error("x[0] and x[1] have the same sign\n");
  28.     if(tol <= 0.0) error("non-positive tol value\n");
  29.     for(;;) {
  30.         xc = 0.5*(x0+x1);
  31.         if(fabs(x0-x1) < tol) return xc;
  32.         fc = zfun(xc);
  33.         if(fc == 0) return xc;
  34.         if(f0*fc > 0.0) {
  35.             x0 = xc;
  36.             f0 = fc;
  37.         }
  38.         else {
  39.             x1 = xc;
  40.             f1 = fc;
  41.         }
  42.     }
  43. }
  44.  
  45. zero_find(void *f, double *x, double *tol)
  46. {
  47.     func = f;
  48.     x[0] = zero_approx(zfun, x[0], x[1], tol[0]);
  49. }
  50.