Skip to content

Instantly share code, notes, and snippets.

@ykare
Created November 22, 2020 09:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ykare/98f9279d1a73473642d40422010623a1 to your computer and use it in GitHub Desktop.
Save ykare/98f9279d1a73473642d40422010623a1 to your computer and use it in GitHub Desktop.
モンテカルロ法で Pi を計算
package test;
import java.util.concurrent.Callable;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.IntStream;
public class PiTest {
public static void main(String[] args) {
final int N = 100_000_000;
task("calcPi(for loop)", () -> calcPi(N));
task("calcPi(Stream)", () -> calcPiStream(N));
task("calcPi(Stream + Parallel)", () -> calcPiParallel(N));
}
public static void task(String taskName, Callable<Double> callable) {
long t0 = System.currentTimeMillis();
double result = 0;
try {
result = callable.call();
} catch (Exception e) {
e.printStackTrace();
}
long t1 = System.currentTimeMillis();
System.out.printf("%30s\t%18.16f\t%4d msecs\n", taskName, result, t1 - t0);
}
public static double calcPi(int num) {
int count = 0;
for (int i = 0; i < num; i++) {
if (calc()) {
count++;
}
}
return (double)count / num * 4D;
}
public static double calcPiStream(int num) {
long count = IntStream.rangeClosed(1, num).filter(i -> calc()).count();
return (double) count / num * 4D;
}
public static double calcPiParallel(int num) {
long count = IntStream.rangeClosed(1, num).parallel().filter(i -> calc()).count();
return (double) count / num * 4D;
}
public static boolean calc() {
double x = ThreadLocalRandom.current().nextDouble();
double y = ThreadLocalRandom.current().nextDouble();
return (x * x + y * y) <= 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment