Java examples for java.lang:Math Operation
Safely calculate hypotenuse value.
/** Basic numeric operations not included in standard Java run-time library. * * <p>/* w w w. jav a 2s . c o m*/ * The binomial methods are modified from those in the Colt library. * </p> * * <p> * The following methods for trigonometric functions come from the * Sfun class written by Visual Numerics. * </p> * * <ul> * <li>acosh</li> * <li>asinh</li> * <li>atanh</li> * <li>cot</li> * <li>cosh</li> * <li>sinh</li> * <li>tanh</li> * </ul> * * <p> * These methods are covered by the following license. * </p> * * ------------------------------------------------------------------------- * $Id: Sfun.java,v 1.1.1.1 1999/03/05 21:43:39 brophy Exp $ * ------------------------------------------------------------------------- * Copyright (c) 1997 - 1998 by Visual Numerics, Inc. All rights reserved. * * Permission to use, copy, modify, and distribute this software is freely * granted by Visual Numerics, Inc., provided that the copyright notice * above and the following warranty disclaimer are preserved in human * readable form. * * Because this software is licensed free of charge, it is provided * "AS IS", with NO WARRANTY. TO THE EXTENT PERMITTED BY LAW, VNI * DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED * TO ITS PERFORMANCE, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * VNI WILL NOT BE LIABLE FOR ANY DAMAGES WHATSOEVER ARISING OUT OF THE USE * OF OR INABILITY TO USE THIS SOFTWARE, INCLUDING BUT NOT LIMITED TO DIRECT, * INDIRECT, SPECIAL, CONSEQUENTIAL, PUNITIVE, AND EXEMPLARY DAMAGES, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * ------------------------------------------------------------------------- */ //package com.java2s; public class Main { public static void main(String[] argv) throws Exception { double a = 2.45678; double b = 2.45678; System.out.println(hypot(a, b)); } /** Safely calculate hypotenuse value. * * @param a One leg of triangle. * @param b Second leg of triangle. * * @return Hypotenuse value. * * <p> * The hypotenuse value is given mathematically as * the sqrt( a^2 + b^2 ). The method implemented * here reduces the chances of cancellation and * roundoff error. If the |a| > |b|, we compute * the hypotenuse as: * </p> * * <p> * hypotenuse = |a| * sqrt( 1 + (b/a) * (b/a) ) * </p> * * <p> * Otherwise b != 0 compute the hypotenuse as: * </p> * * <p> * hypotenuse = |b| * sqrt( 1 + (a/b) * (a/b) ) * </p> * * <p> * If b is zero, the hypotenuse is zero. * </p> */ public static double hypot(double a, double b) { double r; if (Math.abs(a) > Math.abs(b)) { r = b / a; r = Math.abs(a) * Math.sqrt(1.0D + r * r); } else if (b != 0) { r = a / b; r = Math.abs(b) * Math.sqrt(1.0D + r * r); } else { r = 0.0D; } return r; } }