Java 길찾기/이것이 자바다

[Java] 기본 API 클래스 - Math, Random

Kindbeeeear_ 2022. 3. 7. 19:06

Math 클래스

java.lang.Math 클래스는 수학 계산에 사용할 수 있는 메소드를 제공하고 있다. Math 클래스가 제공하는 메소드는 모두 정적(static)이므로 Math 클래스로 바로 사용이 가능하다. 다음은 Math 클래스가 제공하는 메소드들을 설명한 표이다.

메소드 설명 예제 코드 리턴값
int abs(int a)
double abs(double a)
절대값 int v1 = Math.abs(-5);
double 2 = Math.abs(-3.14);
v1 = 5
v2 = 3.14
double ceil(double a) 올림값 double v3 = Math.ceil(5.3);
double v4 = Math.ceil(-5.3);
v3 = 6.0
v4 = -6.0
double floor(double a) 버림값 double v5 = Math.floor(5.3);
double v6 = Math.floor(-5.3);
v5 = 5.0
v6 = -6.0
int max(int a, int b)
double max(double a, double b)
최대값 int v7 = Math.max(5, 9);
double v8 = Math.max(5.3, 2.5);
v7 = 9
v8 = 5.3
int min(int a, int b)
double min(double a, double b)
최소값 int v9 = Math.min(5, 9);
double v10 = Math.min(5.3, 2.5);
v9 = 5
v10 = 2.5
double random() 랜덤값 double v11 = Math.random(); 0.0<=v11<1.0
double rint(double a) 가까운 정수의 실수값 double v12 = Math.rint(5.3);
double v13 = Math.rint(5.7);
v12 = 5.0
v13 = 6.0
long round(double a) 반올림값 long v14 = Math.round(5.3);
long v15 = Math.round(5.7);
v14 = 5
v15 = 6

 

// MathExample.java -- Math의 수학 메소드
public class MathExample {
    public static void main(String[] args) {
        int v1 = Math.abs(-5);
        double v2 = Math.abs(-3.14);
        System.out.println("v1=" + v1);
        System.out.println("v2=" + v2);

        double v3 = Math.ceil(5.3);
        double v4 = Math.ceil(-5.3);
        System.out.println("v3=" + v3);
        System.out.println("v4=" + v4);
        
        double v5 = Math.floor(5.3);
        double v6 = Math.floor(-5.3);
        System.out.println("v5=" + v5);
        System.out.println("v6=" + v6);
        
        int v7 = Math.max(5, 9);
        double v8 = Math.max(5.3, 2.5);
        System.out.println("v7=" + v7);
        System.out.println("v8=" + v8);
        
        int v9 = Math.min(5, 9);
        double v10 = Math.min(5.3, 2.5);
        System.out.println("v9=" + v9);
        System.out.println("v10=" + v10);
        
        double v11 = Math.random();
        System.out.println("v11=" + v11);
        
        double v12 = Math.rint(5.3);
        double v13 = Math.rint(5.7);
        System.out.println("v12=" + v12);
        System.out.println("v13=" + v13);
        
        long v14 = Math.round(5.3);
        long v15 = Math.round(5.7);
        System.out.println("v14=" + v14);
        System.out.println("v15=" + v15);
        
        double value = 12.3456;
        double temp1 = value * 100;
        long temp2 = Math.round(temp1);
        double v16 = temp2 / 100.0;
        System.out.println("v16=" + v16);
    }
}

 

41 ~ 45라인은 소수 셋째 자릿수에서 반올림하는 코드이다. round() 메소드는 항상 소수점 첫째 자리에서 반올림해서 정수값을 리턴한다. 만약 원하는 소수 자릿수에서 반올림된 값을 얻기 위해서는 반올림할 자릿수가 소수점 첫째 자리가 되도록 10^n을 곱한 후, round() 메소드의 리턴값을 얻는다. 그리고 나서 다시 (10^n).0을 나눠주면 된다.

 

Math.random() 메소드는 0.0과 1.0 사이의 범위에 속하는 하나의 double 타입의 값을 리턴한다. 0.0은 범위에 포함되고 1.0은 포함되지 않는다.

0.0 <= Math.random() < 1.0

Math.random()을 활용해서 1부터 10까지의 정수 난수를 얻고 싶다면 다음과 같은 순서로 연산식을 만들면 된다.

 

1. 각 변에 10을 곱하면 다음과 같이 0.0 <= ... < 10.0 사이의 범위에 속하는 하나의 double 타입의 값을 얻을 수 있다.

0.0 * 10 <= Math.random() * 10 < 1.0 * 10

2. 각 변을 int 타입으로 강제 타입 변환하면 다음과 같이 0 <= ... < 10 사이의 범위에 속하는 하나의 int 타입의 값을 얻을 수 있다.

(int)(0.0 * 10) <= (int)(Math.random() * 10) < (int)(1.0 * 10)

3. 각 변에 1을 더하면 다음괌 같이 1 <= ... < 11 사이의 범위에 속하는 하나의 정수를 얻게 된다.

(int)(0.0 * 10) + 1 <= (int)(Math.random() * 10) + 1 < (int)(1.0 * 10) + 1

4. 이제 start <= ... <(start + n) 범위에 속하는 하나의 정수를 얻기 위함 연산식을 다음과 같이 만들면 된다.

int num = (int)(Math.random() * n) + start

 

다음 MathRandomExample 클래스는 한 번 던져서 나오는 주사위의 눈을 Math.random() 메소드를 이용해서 얻는 방법을 보여준다.

// MathRandomExample.java -- 임의의 주사위의 눈 얻기
public class MathRandomExample {
    public static void main(String[] args) {
        int num = (int)(Math.random()*6) + 1;
        System.out.println("주사위 눈: " + num);
    }
}

 

Random 클래스

java.util.Random 클래스는 난수를 얻어내기 위해 다양한 메소드를 제공한다. Math.random() 메소드는 0.0에서 1 사이의 double 난수를 얻는 데만 사용한다면, Random 클래스는 boolean, int, long, float, double 난수를 얻을 수 있다. 또 다른 차이점은 Random 클래스는 종자값(Seed)을 설정할 수 있다. 종자값은 난수를 만드는 알고리즘에 사용되는 값으로 종자값이 같으면 같은 난수를 얻는다. Random 클래스로부터 Random 객체를 생성하는 방법은 다음 두 가지가 있다.

생성자 설명
Random() 호출 시마다 다른 종자값(현재시간 이용)이 자동 설정된다.
Random(long seed) 매개값으로 주어진 종자값이 설정된다.

 

다음은 Random 클래스가 제공하는 메소드이다.

리턴값 메소드(매개 변수) 설명
boolean nextBoolean() boolean 타입의 난수를 리턴
double nextDouble() double 타입의 난수를 리턴(0.0 <= ~ < 1.0)
int nextInt() int 타입의 난수를 리턴(-(2^31) <= ~ <= (2^31) -1)
int nextInt(int n) int 타입의 난수를 리턴(0 <= ~ < n)

 

다음 예제는 로또의 여섯 숫자를 얻는 방법을 보여준다. 로또는 1 ~ 45 범위의 정수 숫자만 선택할 수 있으므로 nextInt(45) + 1 연산식을 사용하면 된다.

// RandomExample.java -- 로또 번호 얻기
public class RandomExample {
    public static void main(String[] args) {
        // 선택번호
        int[] selectNumber = new int[6]; // 선택 번호 6개가 저장됭 배열 생성
        Random random = new Random(3);   // 선택 번호를 얻기 위한 Random 객체 생성
        System.out.print("선택 번호: ");
        for(int i-=0; i<6; i++) {
            selectNumber[i] = random.nextInt(45) + 1; // 선택 번호를 얻어 배열에 저장
            System.out.print(selectNumber[i] + " ");
        }
        System.out.println();
        
        // 당첨번호
        int[] winningNumber = new int[6];
        random = new Random(5);
        System.out.print("당첨 번호: ");
        for(int i=0; i<6; i++) {
            winningNumber[i] = random.nextInt(45) + 1;
            System.out.print(winningNumber[i] + " ");
        }
        System.out.println();
        
        // 당첨여부
        Arrays.sort(selectNumber);
        Arrays.sort(winningNumber);
        boolean result = Arrays.equals(selectNumber, winningNumber);
        System.out.print("당첨 여부: ");
        if(result) {
            System.out.println("1등에 당첨되셨습니다.");
        } else {
            System.out.println("1등에 당첨되지 않으셨습니다.");
        }
    }
}