Error: C stack usage 7970184 is too close to the limit

QFi picture QFi · Nov 25, 2017 · Viewed 8.5k times · Source

I would like to compute the RSI function, which is given as follows:

RSI = 100 * RS / ( 1 + RS ), where        RS = n_up / n_down

                             and   n_up( t ) = ( 1 - b ) *   n_up( t - 1 )
                                             +       b   *      U( t     ),

                             and n_down( t ) = ( 1 - b ) * n_down( t - 1 )
                                             +       b   *      D( t     ).  

                             where    U( t ) = 1  for P( t ) >  P( t - 1 ) and
                                               0  otherwise;

                             and      D( t ) = 1  for P( t ) <  P( t - 1 ) and
                                               0  otherwise.

So here is my code:

p <- data[,6]


rsi <- function(P,t,n)
{
  U <- function(P,t)
  {
    if (diff(P)[t] > 0) 
    {
      return(1)
    } else {
      return(0)
    }
  }

  D <- function(P,t)
  {
    if (diff(P)[t] < 0) 
    {
      return(1)
    } else {
      return(0)
    }
  }

  recursive.n_up <- function(P,t,b)
  {
    return((1-b)*recursive.n_up(P,t-1,b) + b*U(P,t))
  }

  recursive.n_down <- function(P,t,b)
  {
    return((1-b)*recursive.n_down(P,t-1,b) + b*D(P,t))  
  }

  b <- 2/(n+1)
  rs <- function(P,t,b)
  {
    return(recursive.n_up(P,t,b)/recursive.n_down(P,t,b))
  }
  return(100*rs(P,t,b)/(1+rs(P,t,b)))
}

n <- 14
RSI <- rep(0,length(p)-1)
for (i in 1:length(RSI))
{
  RSI[i] <- rsi(p,i,n)
}

print(RSI)

I get a message error stating:

C stack usage 7970184 is too close to
the limit

So I want to know is my algo design very bad or is this something to expect while using recursive functions? Thank you to help me out to solve this problem.

Answer

Bhas picture Bhas · Nov 25, 2017

I completely agree with the previous answer provided byuser3666197; you don't have a stop condition in your recursive function. It will go on and on and on ....

In addition, you do something very inefficient in the function. You calculate

return( 100 *       rs( P, t, b )
            / ( 1 + rs( P, t, b )
              )
        )  

So rs(...) is being calculated twice with exactly the same parameters. Why not this:

Z <- rs( P, t, b )
return( 100 * Z / ( 1 + Z )

You will have to integrate a proper stop condition.