0
$\begingroup$

Please excuse the crudity / simplicity of this question, hbut I have never really got on too well with Do structures - perhaps I don't use them enough - perhaps I avoid them!

How would I create a do loop that performs a given operation on each new value?

eg

val=10;
Log@val // N
a = 39 - %
b = % - Log@%
c = % - Log@%
d = % - Log@%
e = % - Log@%
ToExpression[CharacterRange["a", "e"]]

Of course it can be done with

f[0] = 10;
f[1] = N[f[0] - Log@f[0]]
f[n_] := f[n - 1] - Log[f[n - 1]]

f[5]

but I was wondering whether Do could do the operation.

$\endgroup$
6
  • $\begingroup$ Is the main goal to do this with a Do loop, or to execute this list of operations? In general, this looks a lot like a FoldList kind of construct. $\endgroup$
    – LLlAMnYP
    Commented May 14, 2015 at 0:51
  • $\begingroup$ @LLlAMnYP yes, would really like to do it with Do $\endgroup$
    – martin
    Commented May 14, 2015 at 0:53
  • 1
    $\begingroup$ Judging by the edit, you might as well f[0]=10.; Do[f[i]=f[i-1]-Log[f[i-1]],{i,n}] $\endgroup$
    – LLlAMnYP
    Commented May 14, 2015 at 0:57
  • 1
    $\begingroup$ (tmp = 10; Do[tmp = N[tmp - Log[tmp]], {#}]; tmp) &... $\endgroup$
    – ciao
    Commented May 14, 2015 at 1:05
  • $\begingroup$ @ciao looks good, but can't get it to work ... sorry, I really am not good with these Do structures $\endgroup$
    – martin
    Commented May 14, 2015 at 1:11

1 Answer 1

6
$\begingroup$

As shown by @LLIAMnYP

Clear[f]

f[0] = 10.; Do[f[i] = f[i - 1] - Log[f[i - 1]], {i, 10}]

The calculated function values are

f /@ Range[0, 10]
{10., 7.69741, 5.65653, 3.92372, 2.55668, 1.61797, 1.1368, 1.00858,
1.00004, 1., 1.}

This sequence can also be generated with NestList

NestList[# - Log[#] &, 10., 10]
{10., 7.69741, 5.65653, 3.92372, 2.55668, 1.61797, 1.1368, 1.00858,
1.00004, 1., 1.}

This sequence converges to 1. with any positive initial value

FixedPoint[# - Log[#] &, .000001]
1.
FixedPoint[# - Log[#] &, 1000000.]
1.

However, the number of terms required for convergence to the fixed point can vary radically

FixedPointList[# - Log[#] &, .000001] // Length
15
FixedPointList[# - Log[#] &, 1000000.] // Length
78633
$\endgroup$
1
  • $\begingroup$ superfast! This is great - and thanks for helping with my Do loop education ;) $\endgroup$
    – martin
    Commented May 14, 2015 at 13:37

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.