2
$\begingroup$

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?

$\endgroup$
  • 3
    $\begingroup$ Try RecurrenceTable instead. $\endgroup$ – Roman Jul 22 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$ – Shredderroy Jul 22 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$ – Shredderroy Jul 22 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 at 15:56
  • 3
    $\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 at 16:31
2
$\begingroup$

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}]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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