Cause of a stack overflow in this method (floating-point math)

c++, stack-overflow

Solution

Likely this method is just the straw that breaks the camel's back. This function will only call itself at most once, so it's not the problem. (Edit: Or it's the NAN issue others point to, which will result in infinite recursion.)

You can easily make the function not recursive anyway, which might be a simpler option.

double norm_cdf(double x) {
    bool negative = x < 0;
    x = abs(x);
    double k = 1.0/(1.0 + 0.2316419*x);
    double k_sum = k*(0.319381530 + k*(-0.356563782 + k*(1.781477937 + k*(-1.821255978 + 1.330274429*k))));

    double result = (1.0/(pow(2*M_PI,0.5)))*exp(-0.5*x*x) * k_sum;
    if (!negative)
        result = 1.0 - result;
    return result;
}

Problem

I occasionally get a stackoverflow exception in this method. ``` double norm_cdf(const double x) { double k = 1.0/(1.0 + 0.2316419*x); double k_sum = k*(0.319381530 + k*(-0.356563782 + k*(1.781477937 + k*(-1.821255978 + 1.330274429*k)))); if (x >= 0.0) { return (1.0 - (1.0/(pow(2*M_PI,0.5)))*exp(-0.5*x*x) * k_sum); } else { return 1.0 - norm_cdf(-x); } } ``` Any suggestions on why i might be getting it ? Any steps I can take to rectify the error ?

Original source