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]=0;
y[1]=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?
RecurrenceTable
instead. $\endgroup$Table[y[i], {i, 2, 100}]
almost instantly, but with lots ofIndeterminate
expressions. By the way, you should add a space between5g[i - 1]
andy[i - 1]
and also betweeng[i - 2]
andy[i - 2]
. Without the spaces I got red error messages. $\endgroup$i = 41
the function returnsComplexInfinity
. All subsequent values that depend on that result areIndeterminate
. But the calculations are almost instantaneous. $\endgroup$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. ThenTable[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$g[41]==1
(check that carefully) and your definition ofy[i]
has1-g[i]
in the denominator so youry[41]
blows up. Every highery[i]
depends on previousy[i]
so all subsequent values blow up. That is whyRecurrenceTable
blows up. That is whyRSolve
blows up. That is why manual calculation blows up. Does that explain it now? $\endgroup$