[Java] Random 클래스

Yujeong·2024년 5월 29일
0

Java

목록 보기
10/22
post-thumbnail

Random 클래스는 java.util 패키지에 소속되어 있으며, 난수를 생성하기 위해 사용된다. 정수나 실수처럼 다양한 타입의 난수를 생성할 수 있는 메서드를 제공하고, 난수 시드(seed)를 설정하여 동일한 난수 시퀀스를 재현할 수 있다.

Random 클래스 기능

메서드설명
random.nextInt()랜덤 int값 반환
nextDouble()0.0d~1.0d 사이의 랜덤 double 값 반환
nextBoolean()랜덤 boolean 값 반환
nextInt(int bound)0~bound의 숫자를 랜덤으로 반환 (0포함, bound 포함 안 함)
nextBytes(byte[] bytes)주어진 바이트 배열을 랜덤 바이트로 채움
nextFloat()0.0f~1.0f 사이의 랜덤 float 값 반환
nextLong()랜덤 long 값 반환
nextGaussian()평균 0.0, 표준 편차 1.0의 랜덤 Gaussian(정규 분포) 값을 반환

예시

public class RandomMain {
    public static void main(String[] args) {
        Random random = new Random();

        // nextInt()
        int randomInt = random.nextInt();
        System.out.println(randomInt); // -1030902881

        // nextDouble()
        double randomDouble = random.nextDouble();
        System.out.println(randomDouble); // 0.050077308419608335

        // nextBoolean()
        boolean randomBoolean = random.nextBoolean();
        System.out.println(randomBoolean); // true

        // nextInt(int bound)
        int bound = 10;
        int randomBoundedInt = random.nextInt(bound); // 0 ~ 9
        System.out.println("0 ~ " + bound + ": " + randomBoundedInt); // 0 ~ 10: 9

        int randomRange2 = random.nextInt(bound) + 1; // 1 ~ 10
        System.out.println("1 ~ 10: " + randomRange2); // 1 ~ 10: 1

        // nextBytes(byte[] bytes)
        byte[] byteArray = new byte[5];
        random.nextBytes(byteArray);
        for (byte b : byteArray) {
            System.out.print(b + " "); // -40 76 13 57 48
        }
        System.out.println();

        // nextFloat()
        float randomFloat = random.nextFloat();
        System.out.println(randomFloat); // 0.8134887

        // nextLong()
        long randomLong = random.nextLong();
        System.out.println(randomLong); // 4518032131419933010

        // nextGaussian()
        double randomGaussian = random.nextGaussian();
        System.out.println(randomGaussian); // 0.7681858274182413
    }
}

시드(Seed)

랜덤 값은 시드(Seed) 값을 사용해서 구한다. 즉, 시드 값이 같으면 항상 같은 결과가 나온다.

  • new Random(): 생성자를 비워두면, System.nanoTime()을 이용하여 복잡한 과정으로 시드값을 생성한다.
  • new Random(int seed): 시드 값을 사용하면, 항상 같은 결과를 얻는다. 그래서 랜덤 값을 얻을 수 없지만, 테스트 코드와 같은 곳에서 결과 검증이 가능하다.

위의 RandomMain 클래스에서 Random의 시드 값을 설정하고, 여러 번 실행해도 같은 결과가 나오는 것을 확인할 수 있다.

// Random random = new Random();
Random random = new Random(1234);
-1517918040
0.2597899429702417
false
0~10: 0
1 ~ 10: 4
34 -57 78 117 -109 
0.3359524
1708976400011174721
-0.32478047603102134

시드 생성

Random 클래스 내의 코드를 살펴보자.

public class Random implements RandomGenerator, java.io.Serializable {
    ...
    public Random() {
        this(seedUniquifier() ^ System.nanoTime());
    }

    private static long seedUniquifier() {
        // L'Ecuyer, "Tables of Linear Congruential Generators of
        // Different Sizes and Good Lattice Structure", 1999
        for (;;) {
            long current = seedUniquifier.get();
            long next = current * 1181783497276652981L;
            if (seedUniquifier.compareAndSet(current, next))
                return next;
        }
    }

    private static final AtomicLong seedUniquifier
            = new AtomicQ `8682522807148012L);

    public Random(long seed) {
        if (getClass() == Random.class)
            this.seed = new AtomicLong(initialScramble(seed));
        else {
            // subclass might have overridden setSeed
            this.seed = new AtomicLong();
            setTi
    }
    ...
}
  • 기본 생성자: Random() 생성자를 사용하면 내부적으로 System.nanoTime()과 seedUniquifier()의 결과를 XOR 연산하여 시드를 설정한다.
  • 시드 제공: Random(long seed) 생성자를 사용하면 사용자가 지정한 시드로 난수 생성기를 초기화한다.

참고
Class Random
Java의 정석
김영한의 실전 자바 - 중급 1편

profile
공부 기록

0개의 댓글

관련 채용 정보