Search code examples
c++for-loopfactorial

Why does for-loop behave differently when counting up vs counting down?


This is a homework question which I recently revisited. It requires me not to use cmath and writes a function to evaluate cos pi/3. The code is

#include <iostream>
using namespace std;

double power(double x, int b) {
    if (b>1) return x*power(x,b-1);
    else if (b==0) return 1;
    else return x;
}

double cosine(double x, int k) {
    double tmp=0;
    for (int n=0; n<=k; n++) {
        tmp += power(-1,n) / factorial(2*n) * power(x,2*n);
    }
    return tmp;
}

int main() {
    double x=3.1415/3; 
    int k=100;
    cout << cosine(x,k) << endl;
}

I have written two versions of double factorial(int a) with for-loops.

One counts up and successfully outputs 0.500027 :

double factorial(int a) {
    double tmp=1;
    for (int i=1; i<=a; i++) {
        tmp*=i;
    }
    return tmp;
}

The other one counts down and outputs inf (but successfully evaluate 4!=24):

double factorial(int a) {
    double tmp=a;
    for (int i=a; i>=1; i--) {
        tmp*=i;
    }
    return tmp;
}

Why does the count down loop fail to give a convergent output?


Solution

  • The second factorial() multiplies a twice. Try this:

    double factorial(int a) {
        double tmp=1; // use 1 instead of a
        for (int i=a; i>=1; i--) {
            tmp*=i;
        }
        return tmp;
    }
    

    Note that using double tmp=a; and initializing i to a-1 is not good because it will make factorial(0) = 0, while factorial(0) should be 1.

    The first implementation also multiplies 1 twice, but multiplying 1 doesn't affect the result.