Unstable.java


Below is the syntax highlighted version of Unstable.java from §9.1 Scientific Computation.


/******************************************************************************
 *  Compilation:  javac Unstable.java
 *  Execution:    java Unstable
 *
 *  Calculate phi^N using the iterative formula
 *
 *          phi^N = phi^(N-1) - phi^(N-2)
 *
 *  At around N = 40 there is serious roundoff error. By N = 100
 *  the computed answer is preposterous.
 *
 *  % java Unstable 10
 *  0.008130618755780361 0.008130618755783355
 *
 *  % java Unstable 20
 *  6.610696098441338E-5 6.610696135189609E-5
 *
 *  % java Unstable 30
 *  5.374453024842296E-7 5.374904998555718E-7
 *
 *  % java Unstable 40
 *  -1.1887788531339538E-9 4.370130339181083E-9
 *
 *  % java Unstable 50               // true answer = 3.5531863700963435E-11
 *  -6.836651014197059E-7 3.5531863700963593E-11
 *
 *
 *  % java Unstable 100              // true answer = 1.2625133380638429E-21
 *  -19241.901833166958 1.262513338063854E-21
 *
 ******************************************************************************/

public class Unstable {

   public static void main(String[] args) {
      int N = Integer.parseInt(args[0]);
      double phi  = 0.5 * (Math.sqrt(5) - 1);    //  0.61803398874989484820
      double phi0 = 1.0;                         // phi^0
      double phi1 = phi;                         // phi^1
      double phi2 = -1.0;                        // needs to be initialized

      for (int i = 2; i <= N; i++) {
         phi2 = phi0 - phi1;
         phi0 = phi1;
         phi1 = phi2;
      }
      StdOut.println(phi2 + " " + Math.pow(phi, N));
   }
}


Copyright © 2000–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:33:43 EDT 2022.