Math 클래스는 기본적인 수학 연산을 수행하는 데 사용되는 메서드로, 모든 메서드가 정적(static)이다. 모든 메서드는 객체를 생성하지 않고도 호출할 수 있으므로, 직접 클래스 이름을 사용하여 어디서든 접근할 수 있다.
메서드가 매우 많다. 대략 많이 사용하는 메서드만 정리해보았다.
메서드 | 설명 |
---|---|
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
}
}