计算PI java

时间:2013-12-01 00:12:01

标签: java bigdecimal pi

我正在尝试编写一个程序,它将使用BigDecimal计算PI,但它的工作原理不正确。你可以帮助我解决错误,或者你知道如何在并行程序中实现高斯 - 勒让德算法的例子。非常感谢!

这是我的代码:

   import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class PI_Epta implements IParallelPiEx {

    public static void main(String[] args) throws InterruptedException {
        PI_Epta pe = new PI_Epta();
        pe.calculatePi(0, 0);
    }

    @Override
    public BigDecimal calculatePi(int numberOfThreads, int precision) {
        BigDecimal PI = new BigDecimal(0.0);
        ExecutorService es = Executors.newFixedThreadPool(4);
        List<Future<BigDecimal>> tasks = new LinkedList<Future<BigDecimal>>();
        for (int i = 0, n = 0; i < 1000000; n++, i += 2500) {
            PiParallel counter = new PiParallel(i, i + 2499, n, PI);
            Future<BigDecimal> task = es.submit(new PiParallel(i, i + 2499, n, PI));
            tasks.add(task);
        }
        try {
            for (Future<BigDecimal> t : tasks) {
                PI = PI.add(t.get());
            }
            PI = PI.multiply(new BigDecimal(4));
            System.out.println(PI);
            // 3.14159265358979323846
        } catch (Exception e) {
            System.err.println(e);
        }
        es.shutdown();
        return PI;
    }
}



import java.math.BigDecimal;
import java.util.concurrent.Callable;

public class PiParallel implements Callable<BigDecimal> {

    BigDecimal pi = new BigDecimal(0.0);

    int s;
    int f;
    int n;

    public PiParallel(int s, int f, int n, BigDecimal pi) {
        this.s = s;
        this.f = f;
        this.n = n;
        this.pi = pi;
    }   

    @Override
    public BigDecimal call() throws Exception {
        for (; s < f; s++) {
            BigDecimal bd = new BigDecimal((1.0 / (1.0 + 2.0 * s))); 
            bd= bd.multiply(new BigDecimal(((s % 2 == 0) ? 1 : (-1))));
            pi = pi.add(bd);
        }       
        return pi;
    }
}

1 个答案:

答案 0 :(得分:0)

由于Gauss-Legendre算法定义A / n + 1是基于A / n计算的,因此无法将其并行化。

您可能想要尝试Bailey-Borwein-Plouffe公式。