Search code examples
crecursionpi

Calculating PI recursively in C


I understand there are probably much better ways of calculating PI, but since I found the Leibniz formula:

enter image description here I decided to implement it in C using recursion:

double pi(int n){
    if(n==1)return 4;
    return 4*pow(-1,n+1)*(1/(2*n-1))+pi(n-1);
}

What I always get when I call the function is just 4.000000, meaning it works for number 1 only; Every other number gives me the same result.

What I'm wondering is why this solution isn't working properly. I've tried writing every step down on paper for different numbers and the logic behind it seems correct.

EDIT: Except for what was provided in the answer (thank you!) it seems like (1/(double)(2*n-1)) instead of just (1/(2*n-1)) fixed the problem as well.


Solution

  • The error is entirely in this term:

    (1/(2*n-1))
    

    Say that n happens to be 3 in this iteration:

    1 / (2 * 3 - 1) == 1 / 5 == 0
    

    (I'll let you figure out why the result is 0, when you think it should be 0.2)


    Hint #1: What is the difference between 1.0 and 1?

    Hint #2: How can you fix the expression by adding just a single character to the expression: .??

    1 has type int, 1.0 has type double
    Change the expression to be (1./(2*n-1))