programing tip

Math.random () 설명

itbloger 2020. 7. 2. 07:59
반응형

Math.random () 설명


이것은 매우 간단한 Java (아마도 모든 프로그래밍에 적용 가능) 질문입니다.

Math.random() 0과 1 사이의 숫자를 반환합니다.

0에서 100 사이의 정수를 반환하려면 다음을 수행하십시오.

(int) Math.floor(Math.random() * 101)

백과 백 사이에서 나는 할 것입니다 :

(int) Math.ceil(Math.random() * 100)

하지만 3에서 5 사이의 숫자를 얻으려면 어떻게해야합니까? 다음 진술과 같습니까?

(int) Math.random() * 5 + 3

나는 알고 nextInt()에서 java.lang.util.Random. 하지만이 작업을 수행하는 방법을 배우고 싶습니다 Math.random().


int randomWithRange(int min, int max)
{
   int range = (max - min) + 1;     
   return (int)(Math.random() * range) + min;
}

randomWithRange(2, 5)10 회 출력 :

5
2
3
3
2
4
4
4
5
4

범위는 포괄적이며, 즉 [2,5]이며 위의 예 min보다 작아야합니다 max.

편집 : 누군가가 시도하고 바보와 반대로가는 경우 minmax, 당신은 코드를 변경할 수 있습니다 :

int randomWithRange(int min, int max)
{
   int range = Math.abs(max - min) + 1;     
   return (int)(Math.random() * range) + (min <= max ? min : max);
}

EDIT2 :double s에 대한 질문은 다음과 같습니다.

double randomWithRange(double min, double max)
{
   double range = (max - min);     
   return (Math.random() * range) + min;
}

그리고 당신이 바보 증거를 원한다면 그것은 단지 :

double randomWithRange(double min, double max)
{
   double range = Math.abs(max - min);     
   return (Math.random() * range) + (min <= max ? min : max);
}

0에서 100 사이의 숫자를 생성하려면 코드는 다음과 같습니다.

(int)(Math.random() * 101);

10에서 20까지의 숫자를 생성하려면 다음을 수행하십시오.

(int)(Math.random() * 11 + 10);

일반적인 경우 :

(int)(Math.random() * ((upperbound - lowerbound) + 1) + lowerbound);

( lowerbound포함하고 upperbound배타적 인 곳).

포함 또는 제외는 upperbound선택 따라 다릅니다. range = (upperbound - lowerbound) + 1그때 upperbound는 포괄적이지만, range = (upperbound - lowerbound)그렇다면 upperbound독점적 이라고 가정 해 봅시다 .

예 : 3-5 사이의 정수를 원한다면 범위가 (5-3) + 1이면 5가 포함되지만 범위가 (5-3)이면 5는 배타적입니다.


Random에있는 자바 클래스 java.util패키지는 목적은보다 나은 서비스를 제공 할 것이다. 그것은 몇 가지가 nextInt()정수를 반환 방법. int 인수를 취하는 것은 0에서 int 사이의 숫자를 생성하며 후자는 포함하지 않습니다.


To generate a number between 10 to 20 inclusive, you can use java.util.Random

int myNumber = new Random().nextInt(11) + 10

Here's a method which receives boundaries and returns a random integer. It is slightly more advanced (completely universal): boundaries can be both positive and negative, and minimum/maximum boundaries can come in any order.

int myRand(int i_from, int i_to) {
  return (int)(Math.random() * (Math.abs(i_from - i_to) + 1)) + Math.min(i_from, i_to);
}

In general, it finds the absolute distance between the borders, gets relevant random value, and then shifts the answer based on the bottom border.

참고URL : https://stackoverflow.com/questions/7961788/math-random-explanation

반응형

'programing tip' 카테고리의 다른 글

HTML  (0) 2020.07.02
오류와 예외의 차이점은 무엇입니까?  (0) 2020.07.02
종속성 속성이란 무엇입니까?  (0) 2020.07.02
왜 (0-6)이 -6 = False입니까?  (0) 2020.07.02
포트는 IPv6에서 어떻게 작동합니까?  (0) 2020.07.02