Math 클래스란?
: 기본 지수, 로그, 제곱근 및 삼각 함수와 같은 기본 숫자 연산을 수행하는 방법이 포함되어 있는 클래스
Math 클래스는 수학에서 자주 사용하는 상수들과 함수들을 미리 구현해 놓은 클래스 라고 생각하면 된다.
**Math 클래스의 모든 메소드는 클래스 메소드(static method)이므로, 객체를 생성하지 않고도 바로 사용 가능**
** Math 클래스는 java.lang 패키지에 포함되어 제공됨**
Math class에 정의되어 있는 클래스 필드
- Math.E : 자연로그(natural logarithms)의 밑(base) 값으로 약 2.718을 의미
- Math.PI : 원의 원주를 지름으로 나눈 비율(원주율) 값으로 약 3.14159를 의미
Math class의 대표적인 메소드
1) Math.abs();
-> 절댓값을 구해주는 메소드 / abs메소드는 입력된 값이 양수이면 그대로, 음수이면 그 값의 절댓값을 반환한다.** 절댓값으로 반환된 값들은, 해당타입 그대로 변환된다.(int 면 int , double이면 double) **
public class Main {
public static void main(String args[]) {
int a = -1;
System.out.println(Math.abs(a));
//결과값은 1이 나온다
}
}
이런식으로 Math.abs()를 이용하면 절댓값을 구할 수 있다.
2) Math.floor(); / Math.ceil(); / Math.round();
-> 소수점 올림 / 내림 / 반올림 해주는 메소드
public class Main {
public static void main(String args[]) {
double a = 1.2345;
double b = 9.8765;
System.out.println(Math.floor(a)); // 결과값 1.0
System.out.println(Math.ceil(a)); // 결과값 2.0
System.out.println(Math.round(a)); // 결과값 1
System.out.println(Math.round(b)); // 결과값 10
}
}
+) round 메소드는 결과값을 '정수'로 반환해준다.
3)Math.max(a, b); / Math.min(a, b);
-> 두 값을 비교하여 더 큰 값 / 작은 값을 반환해주는 메소드
public class Main {
public static void main(String args[]) {
int a = 12;
int b = 13;
double c = 1.23;
double d = 1.22;
System.out.println(Math.max(a,b)); // 더 값이 큰 13으로 출력
System.out.println(Math.min(c,d)); // 더 값이 작은 1.22으로 출력
}
}
4)Math.random();
-> 0.0 이상 1.0 미만의 범위에서 임의의 double형 값을 하나 생성하여 반환하는 메소드
import java.util.Random;
public class Main {
public static void main(String args[]) {
System.out.println(Math.random()); // 출력값 0.0 이상 1.0 미만
System.out.println(Math.random() * 10); // 출력값 1.0이상 10.0 미만
System.out.println(Math.random() * 100); // 출력값 10.0이상 100.0 미만
Random rd = new Random(); // java.util 패키지에 포함된 random 메소드를 이용해도 만들 수 있음
System.out.println(rd.nextInt(100)); //결과값 0~99까지의 '정수'로 출력
}
}
5) Math.sqrt(); Math.pow();
->Math.sqrt() 는 숫자의 제곱근을 반환하는 메소드
Math.pow(base, exponent)는 숫자의 base에 exponent를 제곱한 값을 반환하는 메소드
public class Main {
public static void main(String args[]) {
System.out.println(Math.sqrt(9)); // 3.0이 출력
System.out.println(Math.sqrt(36)); // 6.0이 출력
System.out.println(Math.sqrt(33)); // 약 5.74가 출력
System.out.println(Math.sqrt(-1)); // NaN 출력
//----------------------------------------------//
System.out.println(Math.pow(2,2)); // 4.0 출력
System.out.println(Math.pow(3,5)); // 243.0출력(3의 5제곱 -> 3*3*3*3*3)
System.out.println(Math.pow(-1,0.5)); // NaN 출력(base가 음수이고, exponent가 정수가 아닌경우)
}
}
** Math.sqrt() 은 숫자가 음수이면 NaN(Not a Number)을 반환
** Math.pow(base,exponent) 는 base가 음수이고, exponent가 정수가 아닌경우 NaN(Not a Number)을 반환
출처 : Math (Java Platform SE 7 ) (oracle.com)
Java Platform SE 7
docs.oracle.com
'Java 개념정리' 카테고리의 다른 글
[Java] Queue (0) | 2022.10.04 |
---|---|
[Java] Stack (0) | 2022.10.02 |
[java] Dynamic Programming(DP / 동적 계획법) (0) | 2022.09.27 |
[java] String 클래스 (0) | 2022.08.20 |
[Java] 변수 (0) | 2022.08.17 |