user8962173
user8962173

Reputation:

Calculate PI recursively

Formula (Mathematic background)

I try to calculate PI with the following Method: (Java-Code)

private static double calculate(double k) {
    return (
            ( 3 * Math.pow(2, k-1) ) *
                    Math.sqrt(
                            2 - (2 * Math.sqrt(
                                    1-(
                                            Math.pow((calculate(k-1) / ( 3*Math.pow(2, k-1) )), 2)
                                    )
                            ))
                    )
    );
}

I get an Exception in thread "main" java.lang.StackOverflowError on the line I try to call recursively the method itself.

Any ideas or suggestions?

Upvotes: 2

Views: 695

Answers (1)

OmG
OmG

Reputation: 18838

You can calculate it using tail recursion (dynamic programming) instead of simple recursion, as follows:

private static double calculate(double k) {
    double result = 3 * Math.sqrt(2);
    for(int i = 2; i <= k; i++)
       result = 3*Math.pow(2, k-1)*Math.sqrt(2-(2*Math.sqrt(1-Math.pow(result / ( 3*Math.pow(2, k-1) ), 2)));
    return result;
}

In this approach, you did not need to be worry about stackoverflow. Besides, you have a good performance in implementation and running time such as you want in recursive implementation.

Upvotes: 1

Related Questions