본문 바로가기
Language/Java

[Java API] Math 클래스, Random 클래스

by 클레어몬트 2024. 8. 23.

ㅇMath 클래스: 다양한 수학적 연산을 위한 정적 메서드를 제공하는 유틸리티 클래스

따라서 객체를 생성하지 않고 클래스 이름을 통해 직접 메서드를 호출할 수 있다

package lang.math;

public class MathTest {
    public static void main(String[] args) {
        System.out.println("max(1, 3): " + Math.max(1, 3)); // 최대값
        System.out.println("min(1, 3): " + Math.min(1, 3)); // 최소값
        System.out.println("abs(-1): " + Math.abs(-1)); // 절대값
        System.out.println();
        System.out.println("ceil(10.1): " + Math.ceil(10.1)); // 올림
        System.out.println("floor(24.7): " + Math.floor(24.7)); // 내림
        System.out.println("round(25.5): " + Math.round(25.5)); // 반올림
        System.out.println();
        System.out.println("pow(3, 4) = " + Math.pow(3, 4)); // 3^4
        System.out.println("sqrt(9): " + Math.sqrt(9)); // 제곱근
        System.out.println("random(): " + Math.random()); // 0.0 ~ 1.0 사이 double 값
        System.out.println();
        System.out.println("pi = " + Math.PI);
        System.out.println("e = " + Math.E);
    }
}

 

 아주 정밀한 숫자와 반올림 계산이 필요하다면 BigDecimal 클래스 사용하자

e.g. 금융, 과학 계산 등의 매우 정밀한 계산

 

 

 

ㅇRandom 클래스: 씨드(seed)를 설정할 수 있는 난수 생성 클래스

package lang.math;

import java.util.Random;

public class RandomTest {
    public static void main(String[] args) {
        Random random = new Random();
        // Random random = new Random(100); // 이 씨드 값이 같으면 항상 같은 결과가 출력된다

        System.out.println("randInt: " + random.nextInt()); // 랜덤 int값 반환
        System.out.println("randDouble: " + random.nextDouble()); // 0.0d ~ 1.0d
        System.out.println("randBool: " + random.nextBoolean());
        System.out.println();
        System.out.println("range(0 ~ 9): " + random.nextInt(10)); // 0 ~ 9 까지 출력
        System.out.println("range(10 ~ 19): " + (random.nextInt(10) + 10)); // 10 ~ 19 까지 출력
    }
}

 

 

 

[Math.random() vs Random]

- Math.random(): 간단한 난수 생성이 필요한 경우에 사용된다. 반환값은 항상 0.0 이상 1.0 미만의 double 타입이다.

- Random 클래스: 더 복잡한 난수 생성이 필요한 경우에 사용된다. 다양한 자료형의 난수를 생성할 수 있으며, 시드를 설정하여 난수의 일관성을 유지할 수 있다. 

 

'Language > Java' 카테고리의 다른 글

[Java API] 날짜와 시간 라이브러리  (1) 2024.08.27
[Java API] enum 주요 메서드 정리  (0) 2024.08.24
[Java API] System 클래스  (0) 2024.08.23
[Java API] Class 클래스  (0) 2024.08.23
[Java API] 래퍼 클래스(Wrapper Class)  (0) 2024.08.22