# Most efficient code for a recursion relation

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

e=0;
x=Table[i,{i,-5,5,0.1}];
g[i_]:=g[i]=x[[i]]^2-2*e;
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]);
y=0;
y=0.001;


then I can get y's by

yvals=Table[y[i],{i,2,10}];


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?

• Try RecurrenceTable instead. – Roman Jul 22 at 14:53
• 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. – Shredderroy Jul 22 at 14:55
• For i = 41 the function returns ComplexInfinity. All subsequent values that depend on that result are Indeterminate. But the calculations are almost instantaneous. – Shredderroy Jul 22 at 15:37
• 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,y==1/1000},y,i][]; 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. – Bill Jul 22 at 15:56
• From your definition g==1 (check that carefully) and your definition of y[i] has 1-g[i] in the denominator so your y 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? – Bill Jul 22 at 16:31

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, y == 0.001}, y, {i, 1, 101}]