蒙特卡罗计算多个线程上的 Pi



我用Java编写了一个简单的程序,通过Monte Carlo方法计算Pi。由于您需要大量下降才能使Pi"精确",当然,它变得较慢,因此我决定实现多线程。现在回答我的问题:有没有办法加快计算速度?并且一次只计算每个物理线程一次迭代,还是我的多线程概念完全错误?

这是代码:

public class PiMC{
    public static void main(String[] args) {
        ExecutorService exec=Executors.newCachedThreadPool();
        //Future object is used to get result from a thread
        Future<Double> result0=exec.submit(new Thread1());
        Future<Double> result1=exec.submit(new Thread1());
        Future<Double> result2=exec.submit(new Thread1());
        Future<Double> result3=exec.submit(new Thread1());
        Future<Double> result4=exec.submit(new Thread1());
        Future<Double> result5=exec.submit(new Thread1());
        Future<Double> result6=exec.submit(new Thread1());
        Future<Double> result7=exec.submit(new Thread1());
        try
        {
            System.out.println(((result0.get() + result1.get() + result2.get() + result3.get() + result4.get()+ result5.get() + result6.get() + result7.get()) / Long.MAX_VALUE) * 4);
        }
        catch(InterruptedException e){System.out.println(e);}
        catch(ExecutionException e){System.out.println(e);}
    }
}
class Thread1 implements Callable {
    @Override
    public Double call() throws Exception {
        long drops = Long.MAX_VALUE / 8;
        //long drops = 500;
        double in = 0;
        for (long i = 0; i <= drops; i++) {
            double x = Math.random();
            double y = Math.random();
            if (x * x + y * y <= 1) {
                in++;
            }
        }
        return in;
    }
}

你知道 Long.MAX_VALUE/8 有多大吗?它是 (2^63 - 1)/8,大约是 1e18...相当多(即使今天最好的计算机填满整个建筑物,也至少需要 1000 秒,请参阅评论)。

更好的方法是将以前的计算值与 pi 的当前值进行比较并进行比较。如果差值为 0(由于精度有限而发生 --> eps 是 0>最小的数字,其中 1 + eps != 1)取消执行并返回值:

int sum = 0, drops = 0;
double pi = 0, oldPi;
do {
     oldPi = pi;
     double x = Math.random(), y = Math.random();
     if (x * x + y * y <= 1)
         sum++;
     drops++;
     pi = 4.0 * sum / drops;
} while (pi != oldPi || pi < 3); // pi < 3 to avoid problems when the first
// drops are outside of the circle, pi == 0 would also work, BUT setting
// pi to a value different from 0 at the beginning can still fail with only pi != oldPi

如果你想使用多个线程,这很困难,因为pi值的更新必须同步,我想你不会得到太多。但是,多个线程可以独立计算 pi,您可以比较(或平均)结果。

最新更新