Skip to content

Commit 66fdd21

Browse files
committed
Stabilize Monte Carlo integration with antithetic variates to reduce variance
1 parent 6e9aa61 commit 66fdd21

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

src/main/java/com/thealgorithms/randomized/MonteCarloIntegration.java

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,13 +64,21 @@ private static double doApproximate(Function<Double, Double> fx, double a, doubl
6464
if (!validate(fx, a, b, n)) {
6565
throw new IllegalArgumentException("Invalid input parameters");
6666
}
67-
double totalArea = 0.0;
67+
double total = 0.0;
6868
double interval = b - a;
69-
for (int i = 0; i < n; i++) {
69+
int pairs = n / 2;
70+
for (int i = 0; i < pairs; i++) {
71+
double u = generator.nextDouble();
72+
double x1 = a + u * interval;
73+
double x2 = a + (1.0 - u) * interval;
74+
total += fx.apply(x1);
75+
total += fx.apply(x2);
76+
}
77+
if ((n & 1) == 1) {
7078
double x = a + generator.nextDouble() * interval;
71-
totalArea += fx.apply(x);
79+
total += fx.apply(x);
7280
}
73-
return interval * totalArea / n;
81+
return interval * total / n;
7482
}
7583

7684
private static boolean validate(Function<Double, Double> fx, double a, double b, int n) {

0 commit comments

Comments
 (0)