[Java] Math 클래스

Yujeong·2024년 5월 26일
0

Java

목록 보기
9/22
post-thumbnail

Math 클래스는 기본적인 수학 연산을 수행하는 데 사용되는 메서드로, 모든 메서드가 정적(static)이다. 모든 메서드는 객체를 생성하지 않고도 호출할 수 있으므로, 직접 클래스 이름을 사용하여 어디서든 접근할 수 있다.

Math 클래스 메서드

메서드가 매우 많다. 대략 많이 사용하는 메서드만 정리해보았다.

메서드설명
abs(x)절대값
max(a, b)최댓값
min(a, b)최솟값
exp(x)e^x
log(x)자연 로그
log10(x)로그 10
pow(a, b)a^b
ceil(x)올림
floor(x)내림
rint(x)반올림(double)
round(x)반올림(int)
sin(x)사인
cos(x)코사인
tan(x)탄젠트
toDegrees(x)각도로 변환
sqrt(x)제곱근
cbrt(x)세제곱근
random()0.0~1.0 사이의 무작위 값(double) 생성

메서드 사용해보기

  • 기본 연산
public class MathBasicMain {
	public static void main(String[] args) {
      System.out.println(Math.max(30, 70)); // 70
      System.out.println(Math.min(30, 70)); // 30
      System.out.println(Math.abs(30-70)); // 40
    }
}
  • 지수 및 로그 연산
public class ExponentialLogarithmicMain {
	public static void main(String[] args) {
        System.out.println(Math.exp(1)); // 2.7182818284590455

        System.out.println(Math.log(Math.E)); // 1.0
        System.out.println(Math.log(10)); // 2.302585092994046
        
        System.out.println(Math.pow(2, 3)); // 8.0
        System.out.println(Math.pow(5, 2)); // 25.0
    }
}
  • 반올림 및 정밀도
public class RoundingPrecisionMain {
	public static void main(String[] args) {
        System.out.println(Math.ceil(3.7)); // 4.0
        System.out.println(Math.floor(3.7)); // 3.0
        System.out.println(Math.rint(3.7)); // 4.0
        System.out.println(Math.round(3.7)); // 4
        System.out.println(Math.round(3.7654*100)/100.0); // 3.77(소수점 두 번째 자리까지)
    }
}
  • 삼각함수
public class TrigonometricMain {
	public static void main(String[] args) {
        System.out.println(Math.sin(Math.PI / 2)); // 1.0
        System.out.println(Math.cos(Math.PI)); // -1.0
        System.out.println(Math.tan(Math.PI / 4)); // 0.9999999999999999

        System.out.println(Math.toDegrees(Math.PI)); // 180.0
    }
}
  • 기타
public class MathUtilitiesMain {
	public static void main(String[] args) {
        System.out.println(Math.sqrt(25)); // 5.0
        System.out.println(Math.random()); // 0.5001713465711669
    }
}

참고
Class Math
Java의 정석
김영한의 실전 자바 - 중급 1편

profile
공부 기록

0개의 댓글

관련 채용 정보