Matt Owen

source code for "files/java/Numerical.java"

return to portfolio
  1.  package lobos.never.die;
  2.  
  3.  interface numerical_function {
  4.   public double f(double x);
  5.  }
  6.  
  7.  interface function {
  8.   public double f(double ... x);
  9.  }
  10.  
  11.  public class Numerical {
  12.   /* compute the numerical derivative at a point */
  13.   public static void main(String[] args) {
  14.   numerical_function f = new numerical_function() {
  15.   public double f(double x) { return Math.exp(x)-2; }
  16.   };
  17.  
  18.   System.out.println(nderivative(f, 1));
  19.   }
  20.  
  21.   public static double nderivative(numerical_function f, double x) {
  22.   /* h = 2**-26 */
  23.   final double h = 1/67108864.;
  24.   return (f.f(x+h) - f.f(x-h))/2/h;
  25.   /* return (-f.f(2+2*h) + 8*f.f(x+h) - 8*f.f(x-h) + f.f(x-2*h))/12./h; */
  26.   }
  27.  
  28.   public static double nintegrate(numerical_function f, double a, double b) {
  29.   return 1.;
  30.   }
  31.  
  32.   public static double newtonrhapson(numerical_function f, double x) {
  33.   int iterations = 1000, is_zero_iterations = 20;
  34.  
  35.   double fprime;
  36.  
  37.   do {
  38.   do {
  39.   fprime = nderivative(f, x);
  40.   x += 1/67108864.;
  41.   } while (fprime == 0 && is_zero_iterations-- != 0);
  42.  
  43.   x = x - f.f(x)/fprime;
  44.  
  45.   } while (f.f(x) > 1/67108864. && iterations-- != 0);
  46.  
  47.   return x;
  48.   }
  49.  }