이번 글에서는 자바의 Math 클래스에 대해 간략하게 살펴보겠습니다. 이 클래스의 메서드와 이를 사용하는 방법에 대해 이야기해 보겠습니다. Math 클래스는 java.lang 패키지에 있으며 다양한 수학적 계산을 수행하기 위한 정적 메소드 세트를 제공합니다. 다음은 Math 클래스가 유용할 수 있는 계산의 예입니다.
- 절대값 계산(모듈로 값)
- 삼각함수(사인, 코사인 등) 값 계산
- 다양한 각도로 상승
- 다양한 정도의 뿌리 추출
- 난수 생성
- 반올림
- 등.
- 정적 이중 복근(더블 a)
- 정적 부동 절대(부동 소수점 a)
- 정적 int 절대(int a)
- 정적 긴 복근(긴 a)
public static void main(String[] args) {
System.out.println(Math.abs(-1)); // 1
System.out.println(Math.abs(-21.8d)); // 21.8
System.out.println(Math.abs(4532L)); // 4532
System.out.println(Math.abs(5.341f)); // 5.341
}
삼각함수 값 계산
Math 클래스를 사용하면 사인, 코사인, 탄젠트 등 다양한 삼각 함수를 계산할 수 있습니다. 전체 메소드 목록은 공식 문서 웹사이트에서 찾을 수 있습니다 . 다음은 이러한 방법의 목록입니다.- 정적 이중 죄(이중 a)
- 정적 이중 cos(더블 a)
- 스태틱 더블탠(더블에이)
- 정적 이중 asin(더블 a)
- 정적 이중 acos(더블 a)
- 정적 이중 atan(더블 a)
- 정적 이중 toDegrees(이중 각도)
- 정적 이중 toRadians(이중 각도)
public static void main(String[] args) {
System.out.println(Math.sin(Math.toRadians(0)));
System.out.println(Math.sin(Math.toRadians(30)));
System.out.println(Math.sin(Math.toRadians(90)));
System.out.println(Math.cos(Math.toRadians(0)));
System.out.println(Math.cos(Math.toRadians(30)));
System.out.println(Math.cos(Math.toRadians(90)));
}
프로그램은 다음을 출력합니다:
0.0
0.49999999999999994
1.0
1.0
0.8660254037844387
6.123233995736766E-17
부분적으로 각도를 라디안으로 변환하는 오류로 인해 사인 및 코사인 표와 완전히 일치하지 않습니다.
지수화
숫자를 거듭제곱하기 위해 Math 클래스는 다음 서명이 있는 pow 메서드를 제공합니다.static double pow(double a, double b)
이 메서드는 'a' 매개변수를 'b' 거듭제곱으로 올립니다. 예:
public static void main(String[] args) {
System.out.println(Math.pow(1,2)); // 1.0
System.out.println(Math.pow(2,2)); // 4.0
System.out.println(Math.pow(3,2)); // 9.0
System.out.println(Math.pow(4,2)); // 16.0
System.out.println(Math.pow(5,2)); // 25.0
System.out.println(Math.pow(1,3)); // 1.0
System.out.println(Math.pow(2,3)); // 8.0
System.out.println(Math.pow(3,3)); // 27.0
System.out.println(Math.pow(4,3)); // 64.0
System.out.println(Math.pow(5,3)); // 125.0
}
뿌리 추출
Math 클래스는 제곱근과 세제곱근을 구하는 메서드를 제공합니다. 이 절차를 담당하는 방법은 다음과 같습니다.- 정적 이중 sqrt(더블 a)
- 정적 이중 cbrt(더블 a)
public static void main(String[] args) {
System.out.println(Math.sqrt(4)); // 2.0
System.out.println(Math.sqrt(9)); // 3.0
System.out.println(Math.sqrt(16)); // 4.0
System.out.println(Math.cbrt(8)); // 2.0
System.out.println(Math.cbrt(27)); // 3.0
System.out.println(Math.cbrt(125)); // 5.0
}
난수 생성
난수를 생성하기 위해 Math 클래스는 Random 메서드를 제공합니다. 이 방법은 0.0에서 1.0 사이의 범위에서 임의의 양의 실수(이중) 숫자를 생성합니다. 메소드 서명은 다음과 같습니다.public static double random()
예를 살펴보겠습니다:
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(Math.random());
}
}
기본 메소드를 실행한 후 콘솔에 다음이 표시되었습니다.
0.37057465028778513
0.2516253742011597
0.9315649439611121
0.6346725713527239
0.7442959932755443
약간의 조작을 통해 Math 클래스의 무작위 메소드를 사용하여 특정 범위에 있는 정수 난수를 얻을 수 있습니다. 다음은 두 개의 인수 min과 max를 사용하고 min(포함)에서 max(포함) 범위에 있는 임의의 정수를 반환하는 함수의 예입니다.
static int randomInARange(int min, int max) {
return (int) (Math.random() * ((max - min) + 1)) + min;
}
RandomInARange 메서드를 테스트할 Main 메서드를 작성해 보겠습니다.
public class MathExample {
public static void main(String[] args) {
// Карта, в которой мы будем хранить количество выпадений Howого-то числа
Map<Integer, Integer> map = new TreeMap<>();
// За 10000 операций
for (int i = 0; i < 10000; i++) {
// Сгенерируем рандомное число от -10 включительно до 10 включительно
final Integer randomNumber = randomInARange(-10, 10);
if (!map.containsKey(randomNumber)) {
// Если карта еще не содержит "выпавшего случайного числа"
// Положим его в карту с кол-вом выпадений = 1
map.put(randomNumber, 1);
} else {
// Иначе, увеличим количество выпадений данного числа на 1
map.put(randomNumber, map.get(randomNumber) + 1);
}
}
// Выведем на экран содержимое карты в формате ключ=[meaning]
for (Map.Entry<Integer, Integer> entry : map.entrySet()){
System.out.println(String.format("%d=[%d]", entry.getKey(), entry.getValue()));
}
}
static int randomInARange(int min, int max) {
return (int) (Math.random() * ((max - min) + 1)) + min;
}
}
기본 메서드를 실행한 후 출력은 다음과 같습니다.
-10=[482]
-9=[495]
-8=[472]
-7=[514]
-6=[457]
-5=[465]
-4=[486]
-3=[500]
-2=[490]
-1=[466]
0=[458]
1=[488]
2=[461]
3=[470]
4=[464]
5=[463]
6=[484]
7=[479]
8=[459]
9=[503]
10=[444]
Process finished with exit code 0
반올림
Java에서 숫자를 반올림하는 데 사용되는 도구 중 하나는 Math 클래스의 메서드입니다. 더 정확하게 말하면 원형, 천장 및 바닥 방법은 다음과 같습니다.- 정적 긴 라운드(더블 a)
- 정적 int 라운드(float a)
- 정적 이중 바닥(더블에이)
- 정적 이중 천장(더블 a)
public static void main(String[] args) {
System.out.println(Math.round(1.3)); // 1
System.out.println(Math.round(1.4)); // 1
System.out.println(Math.round(1.5)); // 2
System.out.println(Math.round(1.6)); // 2
System.out.println(Math.floor(1.3)); // 1.0
System.out.println(Math.floor(1.4)); // 1.0
System.out.println(Math.floor(1.5)); // 1.0
System.out.println(Math.floor(1.6)); // 1.0
System.out.println(Math.ceil(1.3)); // 2.0
System.out.println(Math.ceil(1.4)); // 2.0
System.out.println(Math.ceil(1.5)); // 2.0
System.out.println(Math.ceil(1.6)); // 2.0
}
결론
이번 글에서는 Math 수업을 피상적으로 살펴보았습니다. 우리는 이 클래스를 사용하여 다음을 수행하는 방법을 살펴보았습니다.- 모듈로 값을 계산합니다.
- 삼각함수 값을 계산합니다.
- 숫자를 거듭제곱으로 올리세요.
- 제곱근과 세제곱근을 추출합니다.
- 난수를 생성합니다.
- 둥근 숫자.
GO TO FULL VERSION