본문 바로가기

language/java

8. [java] 랜덤변수 생성하기 (Math.random,Random클래스)

728x90
반응형

자바에서 랜덤변수를 생성하는 방법에는 크게 2가지 방법이 있다.

우선 컴퓨터에선 난수를 쉽게 만들수가 없다. 정해진 입력에 따라 정해진 값을 주는게 컴퓨터의 선택이다.

따라서 컴퓨터는 매우 빠른 시간 (몇 밀리초)단위로 계속 다른값을 줌으로써 사람이 보기에는 임의의 값이 나오는 것처럼 보이게 한다. 따라서 시간에 따른 값을 주는 seed 값 이라는게 존재한다.

첫번째 방법부터 알아보자.

자바에선 Math.random() 함수를 제공해준다. 이 함수는 0이상 1미만의 구간에서 부동소숫점의 랜덤변수를 만들어준다.

Math.random() 함수는 seed값을 조정할수가 없다.

우선 사용예시를 보겠다.

package chapter4;

public class random {
	public static void main(String[] args) {
		double A = Math.random();
		double B = Math.random();
		double C = Math.random();
		
		System.out.println(A);
		System.out.println(B);
		System.out.println(C);
	}
}

위와 같은 결과가 나왔다. 실제로 매우 짧으시간 사이에 다른 변수값을 주는것을 확인할 수 있었다.

하지만 보통 사용자들은 소수점의 난수를 원하는 것이 아니라 정수의 난수값을 원한다.

 

package chapter4;

public class random {
	public static void main(String[] args) {
		int A = (int)(Math.random()*10 + 1);
		int B = (int)(Math.random()*10 + 1);
		int C = (int)(Math.random()*10 + 1);
		
		System.out.println(A);
		System.out.println(B);
		System.out.println(C);
	}
}

그래서 1~10 사이의 정수값을 원한다고 하면 위와 같이 값을 변경해준다. Math.random()에 원하는 범위만큼을 곱해주고 그것을 int형으로 변형시킨 후에 0이라는 값을 얻기가 싫다면 + 1 을 해주면 된다. 만약 +1 을 해주지 않으면 0~9의 값이 나올 것이다.

하지만 Math.random() 보다도 사용하기 편하고 시드값도 줄 수 있는 Random클래스가 존재한다.

 

Random 클래스의 경우에는 시드값도 직접 설정해줄수 있고, 원하는 타입의 난수를 얻을수도 있습니다.

package chapter4;

import java.util.Random;

public class random {
	public static void main(String[] args) {
		Random random = new Random();
		random.setSeed(System.currentTimeMillis());
		//시드값 설정
		
		System.out.println(random.nextInt());
		System.out.println(random.nextInt(10));
		//int 범위 설정 (0~9)
		System.out.println(random.nextBoolean());
		System.out.println(random.nextLong());
		System.out.println(random.nextFloat());
		System.out.println(random.nextDouble());
		System.out.println(random.nextGaussian());
	}
}

그리고 이것은 결과값이다. 사용하기 편리함에 있어서 Math.random(); 을 이용하는것보다

Random 클래스를 이용하는게 더 다양하고 쉽게 사용할 수 있다.

 

반응형