1

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.

randomuser
  • 299
  • 1
  • 4
  • 11
  • this formula doen not fit into recursible algorithm, use iteration, not recursion – Jacek Cz Mar 22 '18 at 17:37
  • BTW using such expression like `pow()` is extremely in-optimal – Jacek Cz Mar 22 '18 at 17:38
  • Unfortunately, since I'm taking algorithms and data structure, this is something I have to know how to do using recursion. I've decided that this formula would probably be the best to implement. I'd be glad if I wouldn't ever have to use recursion except for web scraping. – randomuser Mar 22 '18 at 17:41

1 Answers1

7

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))

abelenky
  • 63,815
  • 23
  • 109
  • 159