0

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!

hollaholl
  • 93
  • 1
  • 2
  • 10

1 Answers1

1

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.

Alex Lop.
  • 6,810
  • 1
  • 26
  • 45
  • Wow, very silly mistake. So it was my recursive calculation, not the stirling calculation! Thank you very much :) – hollaholl Nov 02 '15 at 07:54