이 쉬운 프로그램은 다트 던지기를 사각형으로 시뮬레이션하여 파이의 추정치를 계산합니다.다른 대안 rand.nextDouble() beetwen -1 and 1
Сonditions는 :는 임의의 부동 소수점 숫자를 생성하고 X에 저장
사이 -1과 1이다 있도록 변환. y에 대해서도 반복하십시오. (x, y)가 (0, 0)과 (x, y) 사이의 거리가 < = 1인지 확인하십시오.
이 후 ratio hits/tries
은 대략 비율은 circle area/square area = pi/4
과 동일합니다. (정사각형은 1/1).
코드 :
public class MonteCarlo {
public static void main(String[] args)
{
System.out.println("Number of tries");
Random generator = new Random(42);
Scanner in = new Scanner(System.in);
int tries = in.nextInt();
int hits = 0;
double x, y;
for (int i = 1; i <= tries; i++)
{
// Generate two random numbers between -1 and 1
int plusOrMinus = generator.nextInt(1000);
if (plusOrMinus > 500) x = generator.nextDouble();
else x = -generator.nextDouble();
plusOrMinus = generator.nextInt(10000);
if (plusOrMinus > 5000) y = generator.nextDouble();
else y = -generator.nextDouble();
if (Math.sqrt((x * x) + (y * y)) <= 1) // Check whether the point lies in the unit circle
{
hits++;
}
}
double piEstimate = 4.0 * hits/tries;
System.out.println("Estimate for pi: " + piEstimate);
}
}
테스트 출력 :
Actual output Expected output
-----------------------------------------------
Number of tries Number of tries
1000 1000
- Estimate for pi: 3.176 Estimate for pi: 3.312
Actual output Expected output
-----------------------------------------------------
Number of tries Number of tries
1000000 1000000
- Estimate for pi: 3.141912 Estimate for pi: 3.143472
어쩌면이 해결책을 찾기 위해 다른 방법이 존재 하는가? 제안 사항.
테스트 출력에서 프로그램이 pi (3.141592)를 예상보다 잘 수행 한 것 같습니다. 나는 그것을 좋은 것으로 클래스화할 것이다. (나는 우연히 우연히 만날 것이지만 무작위 적으로 랜덤에 대한 다른 시드는 아마도 다른 결과를 줄 것이다.) –