3
$\begingroup$

Being new to Mathematica, I try to follow the suggestions of using NestList, Map, Table instead of For/While loops. Things have gone well so far, until I face this problem. I now want my function f to calculate the next result, assume that it is f[f[f[x]]], using the two last results, namely f[f[x]] and f[x]. Can I achieve that goal without using For/While/Do loops?

To make the question more specific and easier to answer, this is my code:

LocalPotential[{v0_, va_, vab_}] := Module[
   {potential = v0, grad = va, hess= vab, deltavab, next},
   potential += deltaphi.grad + (1./2.)*(deltaphi.hess.deltaphi);
   grad += hess.deltaphi;
   hess = MyHessian[hess, grad];
   next = {potential, grad, hess};
   next
]

totallist =  Table[
   NestList[LocalPotential, {Potential0[n, 100.], Gradient0[n], DBH[n]}, nstep], 
   {i, 1, realisation}
 ];

I now want my function MyHessian to calculate the next result using not just the previous one but also the one before that, i.e. va[n-1] and va[n-2]. What should I do? Thanks a million in advance!

$\endgroup$

1 Answer 1

4
$\begingroup$

Here is a hint.

Consider you want to implement a function $f(n)=2^n$ using NetList. You will do something like this:

NestList[#*2&,1,5]

So we used the fact that $f(n+1)=2f(n)$.

Now we will implement Fibonacci sequence where $g(n)=g(n-1)+g(n-2)$

NestList[{#[[2]],#[[1]]+#[[2]]}&,{0,1},10]
(*{{0,1},{1,1},{1,2},{2,3},{3,5},{5,8},{8,13},{13,21},{21,34},{34,55},{55,89}} *)

What happens here? The function $g$ acts on a pair $g: (x,y)\rightarrow (y,x+y)$. So effectively it saves $y$, i.e. $g(n-1)$, for you to be used during next iteration, where it becomes $g(n-2)$.

In the end we don't need pairs, we need just list of second arguments. So our function becomes:

Last@Transpose@NestList[{#[[2]],#[[1]]+#[[2]]}&,{0,1},10]
(*{1,1,2,3,5,8,13,21,34,55,89 *)

If you are not yet very comfortable with pure functions (#@/& stuff), you can rewrite it as:

g[{x_,y_}]:={y,x+y};
Last@Transpose@NestList[g,{0,1},10]
$\endgroup$

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.