어제 오늘 내일

[Java Math] hypot() 메소드 – 직각삼각형의 빗변 계산 본문

IT/Java

[Java Math] hypot() 메소드 – 직각삼각형의 빗변 계산

hi.anna 2025. 12. 14. 07:13

Math.hypot(x, y)는 피타고라스의 정리를 이용해 √(x² + y²) 값을 계산해 줍니다.
직각삼각형에서 두 변의 길이가 주어졌을 때 빗변 길이를 바로 구할 수 있습니다.

 

1. 기본 사용법

public class MathHypotBasic {
    public static void main(String[] args) {
        System.out.println(Math.hypot(3, 4)); // 5.0
        System.out.println(Math.hypot(5, 12)); // 13.0
    }
}

Math.sqrt(x*x + y*y)와 동일한 결과를 주지만, hypot()은 오버플로우나 언더플로우에 더 안전합니다.

 

2. 음수 입력

public class MathHypotNegative {
    public static void main(String[] args) {
        System.out.println(Math.hypot(-3, 4)); // 5.0
    }
}

제곱 후 합산하기 때문에 입력값의 부호는 결과에 영향을 주지 않습니다.

 

3. 활용 예제: 좌표 거리 구하기

public class MathHypotDistance {
    public static void main(String[] args) {
        int x1 = 1, y1 = 2;
        int x2 = 4, y2 = 6;

        double distance = Math.hypot(x2 - x1, y2 - y1);
        System.out.println("두 점 사이의 거리 = " + distance); // 5.0
    }
}

2차원 평면에서 두 점 사이의 유클리드 거리를 구할 때 유용합니다.

 

4. 활용 예제: 벡터 크기 계산

public class MathHypotVector {
    public static void main(String[] args) {
        double vx = 6;
        double vy = 8;

        double magnitude = Math.hypot(vx, vy);
        System.out.println("벡터 크기 = " + magnitude); // 10.0
    }
}

그래픽스, 물리 시뮬레이션 등에서 벡터의 길이를 구할 때 간단히 활용할 수 있습니다.

 

결론

  • Math.hypot(x, y) → √(x² + y²) 반환
  • sqrt(x*x + y*y)와 같지만 더 안전한 구현
  • 좌표 거리, 벡터 크기, 기하학 계산에 자주 활용

 

반응형
Comments