본문 바로가기
Java/Java Basics

자바(Java) 난수 생성 (random number)

by ITmin 2022. 1. 18.

Java에서 난수 생성 방법은 2가지이다. 

1. java.lang.Math class의 정적메소드 random() 메소드 사용

2. janva.util.Random class 사용

 

첫 번째 방법인 Math class의 Math.random() 메소드는 0.0이상 1.0미만의 double 난수를 생성하고

두 번째 방법인 Random class는 int, long, float, double, boolean의 난수를 생성한다. 

 

또한 난수 생성시 사용되는 값인 seed 값은 난수 발생시 기준이 되는 값(종자값)이다.

seed 값이 동일하면 같은 난수가 발생되지만 변하는 값을 seed 값으로 두면 항상 다른 난수가 생성된다. 

 

 


 

Math.random()

Math 클래스는 java.lang 패키지에 포함되어 있으므로 import할 필요가 없다. Math.random() 메소드는 정적(static) 메소드이므로 객체를 생성하지 않고 Math.random(); 으로 바로 사용한다. 

 

public class MathRandom {
    public static void main(String[] args){
    
        double num = Math.random();
        int num2 = (int) (Math.random()*6) +1;
        // 주사위처럼 1~6까지 수 랜덤 지정
        
        System.out.println(num);
        System.out.println(num2);
    }
}

 

결과값

 

 

위 식의 5번째 줄을 보자.

Math.random()을 int로 타입변환하여 정수로 사용하는 방법은 다음과 같다.

 

int num2 = (int) (Math.random()*6) +1;

 

위 코드 블럭은 주사위의 1~6까지 숫자 중 임의로 정수를 얻는 방법이다.

0.0 ≤ Math.random() < 1.0 이므로 6을 곱하면

0.0 ≤ Math.random()*6 < 6.0 이고 여기에 다시 1을 더하면

1.0 ≤  (Math.random()*6) +1 < 7.0 이 된다. 

Math.random()은 double 타입이기 때문에 이를 int로 타입 변환하면 1 ≤ (int) (Math.random()*6) +1 < 7 이 되므로 랜덤으로 나올 수 있는 정수는 1,2,3,4,5,6이 된다. 

 

 


 

Random class

Random 클래스는 Math.random()과 달리 import가 필요하다. seed 값을 생략 혹은 따로 설정 할 수도 있고 Random 클래스 내에 주요 메서드가 여러가지가 있다. 

 

package exam01_random;

import java.util.Random;

public class RandomClass {
    public static void main(String[] args){
        Random rand = new Random();  // 랜덤 객체 생성 (디폴트 시드값 : 현재시간)
        // rand.setSeed(System.currentTimeMillis()); -> 시드값 따로 설정 가능

        System.out.println(rand.nextInt());       // 무작위 int 값
        System.out.println(rand.nextDouble());    // 무작위 double 값
        System.out.println(rand.nextBoolean());   // 무작위 boolean 값
        System.out.println(rand.nextLong());      // 무작위 long 값
        System.out.println(rand.nextFloat());     // 무작위 float 값
        System.out.println(rand.nextGaussian());  // 무작위 gaussian 값 (평균 0 표준편차 1.0인 정규분포 난수)

        // 원하는 자리수까지만
        int bound = 100;
        int bound2 = 1000;
        System.out.println(rand.nextInt(bound));  // 100 미만 랜덤 정수
        System.out.println(rand.nextInt(bound2)); // 1000 미만 랜덤 정수
        System.out.println(rand.nextInt(10));  // 10 미만 랜덤 정수
    }
}

 

위 코드를 실행하면 랜덤 값이기 때문에 실행할 때마다 다른 값이 나오지만 예시로 한 실행 값은 다음과 같다.  

댓글