Close

Java - Math.hypot() Examples

Java Java API 


Class:

java.lang.Math

java.lang.Objectjava.lang.Objectjava.lang.Mathjava.lang.MathLogicBig

Method:

public static double hypot(double x,
                           double y)

Returns sqrt(x2 +y2) without intermediate overflow or underflow.


Examples


package com.logicbig.example.math;

public class HypotExample {

public static void main(String... args) {
findHypot(3, 5);
findHypot(-4, 3);
findHypot(Double.MAX_VALUE, 5);
findHypot(Double.POSITIVE_INFINITY, 12);
findHypot(303, Double.NEGATIVE_INFINITY);
}

private static void findHypot(double x, double y) {
double getHypot_value = Math.hypot(x, y);
System.out.printf(" Math.hypot(%s,%s) = %s%n", x, y, getHypot_value);
}
}

Output

 Math.hypot(3.0,5.0) = 5.830951894845301
Math.hypot(-4.0,3.0) = 5.0
Math.hypot(1.7976931348623157E308,5.0) = 1.7976931348623157E308
Math.hypot(Infinity,12.0) = Infinity
Math.hypot(303.0,-Infinity) = Infinity




package com.logicbig.example.math;

public class HypotExample2 {

public static void main(String... args) {
side_values(3, 4);
side_values(6, 8);
side_values(11, 13);
}

private static void side_values(double a, double b) {
// Pythagorean Theorem
System.out.println("-----------");
double hyp = a * a + b * b;
System.out.printf(" Without using Math.hypot() = %s%n", Math.sqrt(hyp));
double hypot = Math.hypot(a, b);
System.out.printf(" With Math.hypot(%s,%s) = %s%n", a, b, hypot);
}
}

Output

-----------
Without using Math.hypot() = 5.0
With Math.hypot(3.0,4.0) = 5.0
-----------
Without using Math.hypot() = 10.0
With Math.hypot(6.0,8.0) = 10.0
-----------
Without using Math.hypot() = 17.029386365926403
With Math.hypot(11.0,13.0) = 17.029386365926403




See Also