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–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:33:43 EDT 2022.