BeneficialCancellation.java


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



/******************************************************************************
 *  Compilation:  javac BeneficialCancellation.java
 *  Execution:    java BeneficialCancellation x
 *
 *  % java BeneficialCancellation 1.0000001
 *  f(1.0000001)     = 0.9999999500000009
 *  g(1.000000001)   = 1.0

 ******************************************************************************/

public class BeneficialCancellation {

    public static double f(double x) {
        double y = x - 1.0;
        double z = Math.exp(y);
        if (z == 1) return z;
        return  Math.log(z) / (z - 1.0);
    }

    public static double g(double x) {
        double y = x - 1.0;
        double z = Math.exp(y);
        if (z == 1) return z;
        return  y / (z - 1.0);
    }


    public static void main(String[] args) {
        double x = Double.parseDouble(args[0]);
        StdOut.println("f(" + x + ")     = " + f(x));
        StdOut.println("g(" + x + ")     = " + g(x));
   }

}


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