Chris Playman
Chris Playman

Reputation: 21

Calculation of the constant e using Java multithreading

I'm trying to calculate e for my assignment using threads for the least amount of time possible, given that the user will pass a variable with the amount of threads that will be used for the calculation, but I can't get my multithreading working properly to achieve some kind of result. I was told that a good method for calculation will be using the following mathematical expression: e = sum( (3-4k^2)/((2k+1)!) ) , where k = (0;infinity). But so far I got only this basic method:

public class MainClass {
    public static long fact(int x) {
        long p = 1;
        for (int i = 1; i <= x; i++)
            p = p * i;
        return p;
    }

    public static void main(String[] args) {
        double e = 1;
        for (int i = 1; i < 50; i++)
            e = e + 1 / (double) (fact(i));
        System.out.print("e = " + e);
    }
}

Upvotes: 1

Views: 358

Answers (1)

Ortomala Lokni
Ortomala Lokni

Reputation: 62605

You can use the Java 8 parrallel Streams it's easier and less error-prone than explcitly creating Threads.

import org.apache.commons.math.util.MathUtils;

...

public static double computeE(){
    return IntStream.iterate(0,k->k+1)
                    .limit(100000)
                    .mapToDouble(k->(3-4*k*k)/MathUtils.factorialDouble(2*k+1))
                    .parallel()
                    .sum();
}

On my machine, it uses the two cores and find e=2.718281828459045 for 10000 iterations which is a value where every digits are correct.

Upvotes: 1

Related Questions