Search code examples
capproximation

Stirling's approximation in c language


I'm trying to write a code in C to calculate the accurate of Stirling's approximation from 1 to 12.

Here's my code:

#define PI 3.1416
#define EULERNUM 2.71828

float stirling_approximation(int n) {
    int fact;
    float stirling, ans;

    fact = factorial(n);
    stirling = sqrt(2.0*PI*n) * pow(n / EULERNUM, n);
    ans = fact / stirling;

    return ans;
}

int factorial(int input) {
    int i;
    int ans = 0;

    for (i = 1; i <= input; i++)
        ans += i;
    return ans;
}

int main(void) {
    int n;
    printf(" n\t Ratio\n");
    for (n = 1; n <= 12; n++) {
        printf("n: %2d\t %f\n", n, stirling_approximation(n));
    }

    return 0;
}

I'm getting the recursive calculation correctly, but my Stirling's approximation method value is way off. And what's even more puzzling is the answers for n = 1, 3 is correct.

I think it has something to do with calling the approximation function from the main function. I know it must be such a simple mistake but I've been trying to fix this for the entire day! Could anyone please help me?

Thank you!


Solution

  • You incorrectly implemented the factorial method

    int factorial(int input) {
        int i;
        int ans = 0;
    
        for (i = 1; i <= input; i++)
            ans += i;
        return ans;
    }
    

    It should be

    int factorial(int input) {
        int i;
        int ans = 1;
    
        for (i = 2; i <= input; i++)
            ans *= i;
        return ans;
    }
    

    I would also change the return value from int to long int.