Pythagoras.java


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



/******************************************************************************
 *  Compilation:  javac Pythagoras.java
 *  Execution:    java Pythagoras a b
 *  
 *  Given a and b, print out sqrt(a*a + b*b). Avoid overflow.
 *
 ******************************************************************************/

public class Pythagoras {


   public static void main(String[] args) {
      double a = Double.parseDouble(args[0]);
      double b = Double.parseDouble(args[1]);
      double r = 0.0;

      if (Math.abs(a) > Math.abs(b)) {
         r = b / a;
         r = Math.abs(a) * Math.sqrt(1 + r*r);
      }
      else if (b != 0) {
         r = a / b;
         r = Math.abs(b) * Math.sqrt(1 + r*r);
      }

      StdOut.println(r);
   }

}


Copyright © 2000–2017, Robert Sedgewick and Kevin Wayne.
Last updated: Fri Oct 20 14:12:12 EDT 2017.