C++ always returns -inf when calculating cosine

Viewed 137

I am attempting to write a function that takes a value x and calculates the cos x by the series expansion, I'm always getting -inf, indifferent which value is read in.

#include <iostream>
#include <math.h>
#include <iomanip>

using namespace std;

int fac(int n){
        return n == 0 || n == 1 ? 1 : n * fac(n-1);
}

int main(){
        double eps = 1e-15;
        double x;
        cin >> x;
        long double ak = 1, sn = 0;
        for(int k=1; abs(ak) > eps * abs(sn); k++){
            double sgn = k % 2 == 0 ? 1 : -1;
            sn += ak;
            ak = sgn * pow(x, 2 * k) / fac(2*k);
        }
        cout << setprecision(4) << setw(5) << "x" << setprecision(15) << setw(20) << "cos x" << endl;
        cout << setprecision(4) << setw(5)<< x << " " << setprecision(15) << setw(20) << sn << endl;
        cout << setw(26) << cos(x) << endl;
        return 0;
}

I debugged the code and at a certain point ak gets -inf. But why?

0 Answers
Related