Search code examples
cmathpiapproximation

Leibniz function in c


I'm looking for a Leibniz approximation of PI in C.

I've tested this function but it does not seem to work:

float leibnizPi(float n){
    double pi=1.0;
    int i;
    int N;
    for (i=3, N=2*n+1; i<=N; i+=2)
        pi += ((i&2) ? -1.0 : 1.0) / i;
    return 4*pi;
}

Solution

  • I've tested you function and it seems to work fine. For n=1000, I get a result of 3.142592.

    How I've tested the function:

    #include <stdio.h>
    
    float leibnizPi(float n) {
        double pi=1.0;
        int i;
        int N;
        for (i=3, N=2*n+1; i<=N; i+=2)
            pi += ((i&2) ? -1.0 : 1.0) / i;
        return 4*pi;
    }
    
    int main(void)
    {
        printf("Pi: %f\n", leibnizPi(1000));
        return 0;
    }