Search code examples
c++visual-c++stack-overflowserieseulers-number

My C++ program has trouble calculating this series for Euler's number


enter image description here

Here is the C++ program i wrote to solve the above series:

#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;

int factorial(int a)
{
    if (a > 1)
        return a * factorial(a - 1);
    else
        return 1;
}

float series(float x, int n, float b)
{
    if (abs(pow(x, n) / factorial(n)) < pow(10, -6) || abs(pow(x, n) / factorial(n)) == pow(10, -6)) { return b; }
    else return b = (pow(x, n) / factorial(n)) + series(x, n + 1, b);
}

int main()
{
    float x;
    cout << "Enter x: "<<endl;
    cin >> x;
    cout << "E^x = " << series(x,0,0);
    system("pause");
    return 0;
}

It works fine when abs(x) < 2 but when abs(x) >= 2 this error appears:

Unhandled exception at 0x00F02539 in 33b.exe: 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x00F22FF8). occurred enter image description here

I want to know why does this happen and how can i fix it?


Solution

  • Your problem is too deep recursion. Consider loop instead.

    float series(float x)
    {
        const float epsilon = 1e-6f;
        double error = 1;
        double res = 1.f;
        int iter = 1;
        while (abs(error) > epsilon) {
            error *= (x / iter++);
            res += error;
            cout << error << endl;
        }
        return res;
    }
    
    int main()
    {
        cout << "E^x = " << series(3);
        system("pause");
        return 0;
    }
    

    To be clearer about what happens:

    When you call a function inside another function, the context of the parent function is saved to make room for the new context. When you make millions of inception, the memory stack in charge to save these context is full and overflows.

    This is a Stack Overflow.