어제 오늘 내일

[Java] Random 클래스의 시드(Seed)란 본문

IT/Java

[Java] Random 클래스의 시드(Seed)란

hi.anna 2025. 3. 18. 06:24

 

시드(Seed)란?

시드(Seed) 는 난수 생성기의 초기값(Starting Value) 입니다.

컴퓨터에서 난수(Random Number)를 생성할 때 완전한 무작위(randomness)는 불가능하기 때문에,

특정한 초기값(Seed) 을 설정하여 유사 난수를 생성합니다.

 

1. 시드(Seed)의 역할

  • 같은 시드 값을 사용하면 항상 같은 난수를 생성.
  • 다른 시드 값을 사용하면 서로 다른 난수를 생성.
  • 시드 값을 기반으로 난수가 결정되므로, 난수의 재현 가능성이 있음.

 

2. 시드를 설정하는 이유

1) 난수의 재현성 보장

  • 동일한 프로그램을 여러 번 실행할 때, 같은 난수를 얻고 싶을 경우 시드를 고정.
  • 테스트 또는 디버깅할 때 동일한 결과를 보장.

2) 완전히 새로운 난수 생성

  • 시드를 현재 시간(System.currentTimeMillis()) 또는 System.nanoTime() 을 기반으로 설정하면,실행할 때마다 다른 난수 생성 가능.

 

3. Java에서 시드 설정 방법

(1) 시드가 없는 Random 객체 (기본값)

import java.util.Random;

public class RandomWithoutSeed {
    public static void main(String[] args) {
        Random random = new Random(); // 시드 미설정 (현재 시간 기반 시드 사용)

        System.out.println("랜덤 값 1: " + random.nextInt(100)); // 0~99
        System.out.println("랜덤 값 2: " + random.nextInt(100));
    }
}
  • 시드를 설정하지 않으면 Random() 객체는 내부적으로 System.nanoTime()을 사용하여 시드를 설정.
  • 따라서, 프로그램을 실행할 때마다 다른 난수를 반환.

 

(2) 고정된 시드 사용 (new Random(seed))

import java.util.Random;

public class RandomWithFixedSeed {
    public static void main(String[] args) {
        Random random = new Random(42); // 고정된 시드 값 설정

        System.out.println("랜덤 값 1: " + random.nextInt(100)); // 항상 같은 난수 리턴
        System.out.println("랜덤 값 2: " + random.nextInt(100)); // 항상 같은 난수 리턴
    }
}
  • Random(42) → 시드가 42로 고정되었기 때문에, 프로그램을 실행할 때마다 항상 같은 난수 반환.

 

(3) 실행할 때마다 다른 난수를 생성하려면 System.currentTimeMillis() 사용

import java.util.Random;

public class RandomWithTimeSeed {
    public static void main(String[] args) {
        long seed = System.currentTimeMillis(); // 현재 시간 기반 시드
        Random random = new Random(seed);

        System.out.println("랜덤 값 1: " + random.nextInt(100));
        System.out.println("랜덤 값 2: " + random.nextInt(100));
    }
}
  • 현재 시간을 시드로 사용하면 매번 실행할 때마다 다른 난수 생성 가능.

 

(4) SecureRandom에서 시드 사용

보안이 중요한 경우, SecureRandom을 사용하여 안전한 난수를 생성할 수 있습니다.

import java.security.SecureRandom;

public class SecureRandomExample {
    public static void main(String[] args) {
        SecureRandom secureRandom = new SecureRandom();
        secureRandom.setSeed(System.currentTimeMillis()); // 현재 시간을 시드로 설정

        System.out.println("보안 난수: " + secureRandom.nextInt(100));
    }
}
  • SecureRandom은 일반 Random보다 예측이 어려운 난수를 생성.

 

4. 시드 설정에 따른 난수 생성 비교

난수 생성 방법 시드 값 결과

난수 생성 방법 시드 값 결과
new Random() 없음(기본값) 실행할 때마다 다른 난수
new Random(42) 42 실행할 때마다 같은 난수
new Random(System.currentTimeMillis()) 현재 시간 실행할 때마다 다른 난수
SecureRandom.setSeed(System.currentTimeMillis()) 현재 시간 보안성이 높은 난수

 

 

정리

  • 시드(Seed)는 난수 생성기의 초기값으로, 이를 설정하면 항상 동일한 난수를 생성할 수 있음.
  • 고정된 시드를 사용하면 테스트와 디버깅에 유용.
  • 시드를 현재 시간(System.currentTimeMillis())으로 설정하면 매번 다른 난수 생성 가능.
  • 보안이 중요한 경우 SecureRandom을 사용하여 안전한 난수 생성.

 

 

 

반응형
Comments