IT

범위에서 임의의 이중 생성

lottoking 2020. 7. 11. 09:17
반응형

범위에서 임의의 이중 생성


나는 다음과 같은 두 복식이 있습니다.

double min = 100;
double max = 101;

랜덤 생성기로 최소값과 최대 값 사이의 이중 값을 선택합니다.

Random r = new Random();
r.nextDouble();

그러나 여기서는 존재하지 않습니다.


사이의 임의의 값을 생성하는 방법 rangeMinrangeMax:

Random r = new Random();
double randomValue = rangeMin + (rangeMax - rangeMin) * r.nextDouble();

이 질문은 Java 7 릴리스 이전에 요청하는 이제 Java 7 (이상) API를 사용하는 또 다른 방법이 있습니다.

double random = ThreadLocalRandom.current().nextDouble(min, max);

nextDouble최소 (포함)와 최대 (제외) 사이의 의사 난수 double 값을 반환합니다. 경계가 사용 int가능할 수도 있습니다 double.


이것을 사용하십시오 :

double start = 400;
double end = 402;
double random = new Random().nextDouble();
double result = start + (random * (end - start));
System.out.println(result);


편집하다 :

new Random().nextDouble(): 0과 1 사이의 숫자를 임의로 생성합니다.

start: 시작 번호, 번호를 "오른쪽으로"이동

end - start: 간격. random은 0에서 1까지의 숫자를주기 때문에이 숫자의 0 %에서 100 %까지를 제공합니다.


편집 2 : Tks @daniel 및 @aaa bbb. 내 첫 대답은 틀렸다.


import java.util.Random;
    public class MyClass {
         public static void main(String args[]) {
          Double min = 0.0; //  Set To Your Desired Min Value
          Double max = 10.0; //    Set To Your Desired Max Value
          double x = (Math.random() * ((max - min) + 1)) + min; //    This Will Create 
          A Random Number Inbetween Your Min And Max.
          double xrounded = Math.round(x * 100.0) / 100.0; // Creates Answer To 
          The Nearest 100 th, You Can Modify This To Change How It Rounds.
          System.out.println(xrounded); //    This Will Now Print Out The 
          Rounded, Random Number.
         }
    }

Random random = new Random();
double percent = 10.0; //10.0%
if (random.nextDouble() * 100D < percent) {
    //do
}

참고 URL : https://stackoverflow.com/questions/3680637/generate-a-random-double-in-a-range

반응형