What is the most efficient code for the following formula:

$y_{n+1}=\frac {2y_n-y_{n-1}+5g_n y_n+g_{n-1}y_{n-1}}{1-g_{n+1}}$

where $g_n$ is a variable.

I have tried this code

y[i_]:=y[i]= (2 y[i - 1] - y[i - 2] + 5*g[i - 1]*y[i - 1] + 
  g[i - 2]*y[i - 2])/(1 - g[i]);

then I can get y's by


It works, but when I change the i value to 100 in the last line, it runs for a very long time. It seems that it is a very inefficient code. How can I convert it into an efficient one?

  • 3
    $\begingroup$ Try RecurrenceTable instead. $\endgroup$
    – Roman
    Jul 22, 2019 at 14:53
  • $\begingroup$ I get the result for Table[y[i], {i, 2, 100}] almost instantly, but with lots of Indeterminate expressions. By the way, you should add a space between 5g[i - 1] and y[i - 1] and also between g[i - 2] and y[i - 2]. Without the spaces I got red error messages. $\endgroup$ Jul 22, 2019 at 14:55
  • 1
    $\begingroup$ For i = 41 the function returns ComplexInfinity. All subsequent values that depend on that result are Indeterminate. But the calculations are almost instantaneous. $\endgroup$ Jul 22, 2019 at 15:37
  • 1
    $\begingroup$ For "most efficient" evaluate this g[i_]:=(-5+(i-1)/10)^2; sol=y/.RSolve[{y[i]==(2 y[i-1] - y[i-2] + 5*g[i-1]*y[i-1] + g[i-2]*y[i-2])/(1 - g[i]),y[0]==0,y[1]==1/1000},y,i][[1]]; and let it finish. Then Table[sol[i],{i,2,20}]+0. will efficiently calculate your result. You can compare the results from that with your original code and should see that they are the same. $\endgroup$
    – Bill
    Jul 22, 2019 at 15:56
  • 4
    $\begingroup$ From your definition g[41]==1 (check that carefully) and your definition of y[i] has 1-g[i] in the denominator so your y[41] blows up. Every higher y[i] depends on previous y[i] so all subsequent values blow up. That is why RecurrenceTable blows up. That is why RSolve blows up. That is why manual calculation blows up. Does that explain it now? $\endgroup$
    – Bill
    Jul 22, 2019 at 16:31

1 Answer 1


As @Roman said, the RecurrenceTable command worked as follows

RecurrenceTable[{y[i + 1] == (2 y[i] - y[i-1] + 5 * g[i] * y[i] + g[i-1]*y[i-1])/(1 - g[i+1]), y[0] == 0, y[1] == 0.001}, y, {i, 1, 101}]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.