일반 Generate random numbers (Random.java)

황제낙엽 2017.07.02 22:37 조회 수 : 1079

sitelink1 http://www.javapractices.com/topic/TopicAction.do?Id=62 
sitelink2  
sitelink3  
sitelink4  
sitelink5  
sitelink6  
Random.nextInt(number)함수는 0부터 number를 제외한 이하의 수치값을 반환한다

 

 

There are two principal means of generating random (really pseudo-random) numbers:

  • the Random class generates random integers, doubles, longs and so on, in various ranges.
  • the static method Math.random generates doubles between 0 (inclusive) and 1 (exclusive).

To generate random integers:

  • do not use Math.random (it produces doubles, not integers)
  • use the Random class to generate random integers between 0 and N.

To generate a series of random numbers as a unit, you need to use a single Random object - do not create a new Random object for each new random number.

Other alternatives are:

Here are some examples using Random.

Example 1 

import java.util.Random;

/** Generate 10 random integers in the range 0..99. */
public final class RandomInteger {
  
  public static final void main(String... aArgs){
    log("Generating 10 random integers in range 0..99.");
    
    //note a single Random object is reused here
    Random randomGenerator = new Random();
    for (int idx = 1; idx <= 10; ++idx){
      int randomInt = randomGenerator.nextInt(100);
      log("Generated : " + randomInt);
    }
    
    log("Done.");
  }
  
  private static void log(String aMessage){
    System.out.println(aMessage);
  }
}
 


Example run of this class:

Generating 10 random integers in range 0..99.
Generated : 44
Generated : 81
Generated : 69
Generated : 31
Generated : 10
Generated : 64
Generated : 74
Generated : 57
Generated : 56
Generated : 93
Done.

Example 2

This example generates random integers in a specific range. 

import java.util.Random;

/** Generate random integers in a certain range. */
public final class RandomRange {
  
  public static final void main(String... aArgs){
    log("Generating random integers in the range 1..10.");
    
    int START = 1;
    int END = 10;
    Random random = new Random();
    for (int idx = 1; idx <= 10; ++idx){
      showRandomInteger(START, END, random);
    }
    
    log("Done.");
  }
  
  private static void showRandomInteger(int aStart, int aEnd, Random aRandom){
    if (aStart > aEnd) {
      throw new IllegalArgumentException("Start cannot exceed End.");
    }
    //get the range, casting to long to avoid overflow problems
    long range = (long)aEnd - (long)aStart + 1;
    // compute a fraction of the range, 0 <= frac < range
    long fraction = (long)(range * aRandom.nextDouble());
    int randomNumber =  (int)(fraction + aStart);    
    log("Generated : " + randomNumber);
  }
  
  private static void log(String aMessage){
    System.out.println(aMessage);
  }
} 



An example run of this class:

Generating random integers in the range 1..10.
Generated : 9
Generated : 3
Generated : 3
Generated : 9
Generated : 4
Generated : 1
Generated : 3
Generated : 9
Generated : 10
Generated : 10
Done.

Example 3

This example generates random floating point numbers in a Gaussian (normal) distribution. 

import java.util.Random;

/** 
 Generate pseudo-random floating point values, with an 
 approximately Gaussian (normal) distribution.

 Many physical measurements have an approximately Gaussian 
 distribution; this provides a way of simulating such values. 
*/
public final class RandomGaussian {
  
  public static void main(String... aArgs){
    RandomGaussian gaussian = new RandomGaussian();
    double MEAN = 100.0f; 
    double VARIANCE = 5.0f;
    for (int idx = 1; idx <= 10; ++idx){
      log("Generated : " + gaussian.getGaussian(MEAN, VARIANCE));
    }
  }
    
  private Random fRandom = new Random();
  
  private double getGaussian(double aMean, double aVariance){
    return aMean + fRandom.nextGaussian() * aVariance;
  }

  private static void log(Object aMsg){
    System.out.println(String.valueOf(aMsg));
  }
} 



An example run of this class:

Generated : 99.38221153454624
Generated : 100.95717075067498
Generated : 106.78740794978813
Generated : 105.57315286730545
Generated : 97.35077643206589
Generated : 92.56233774920052
Generated : 98.29311772993057
Generated : 102.04954815575822
Generated : 104.88458607780176
Generated : 97.11126014402141
번호 제목 글쓴이 날짜 조회 수
246 이미지 파일의 화면사이즈와 포맷(확장자) 구하기 황제낙엽 2018.04.01 974
245 File 을 다루기 위한 유틸 클래스 file 황제낙엽 2018.02.28 759
244 상수의 데이터 타입 황제낙엽 2018.01.26 799
243 Java에서 User-Agent 파써 사용하기 황제낙엽 2017.11.20 1077
242 현재 월,일,시간,분,초 등등 가져오기 황제낙엽 2017.11.02 1439
241 날짜, 시간 문자열 값으로 Date 오브젝트로 만들기 >> SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US) 황제낙엽 2017.10.31 2314
240 시스템 속성(System Property) 클래스를 이용하여 jni 라이브러리 사용하기 황제낙엽 2017.09.22 619
239 Java 실행 옵션들 황제낙엽 2017.08.23 3964
238 HttpsURLConnection 을 사용한 SSL서버 접속 file 황제낙엽 2017.08.02 937
237 서버구동시 주기적으로 동작을 수행하는 스레드를 함께 실행하는 서블릿 황제낙엽 2017.08.02 718
236 HttpURLConnection 사용 샘플( JSP , SERVLET ) 황제낙엽 2017.08.01 1084
235 HttpURLConnection 사용하기 황제낙엽 2017.08.01 1228
234 [HttpURLConnection] POST로 파라미터 넘기기 황제낙엽 2017.08.01 1221
233 HttpURLConnection POST 방식 사용하기 황제낙엽 2017.08.01 1201
232 Runtime 클래스를 이용한 윈도우 프로그램 실행 예제 황제낙엽 2017.08.01 814
231 자바 리플렉션(Java Reflection) 간단한 설명 및 사용방법 정리 file 황제낙엽 2017.07.10 623
» Generate random numbers (Random.java) 황제낙엽 2017.07.02 1079
229 쓰레드(Thread)를 중간에 종료시키는 방법 황제낙엽 2017.03.15 5770
228 싱글톤 방식의 테스트용 Temporary Data Access Object 황제낙엽 2017.01.12 2168
227 SimpleDateFormat Symbol file 황제낙엽 2016.12.20 794