开发者

Mathematica: Grokking 'maximal number of evaluations' argument for `NestWhileList`

开发者 https://www.devze.com 2023-01-23 18:40 出处:网络
I am using NestWhileList in a situation where it often hits the \'maximum number of evaluations\'. After getting some curios results, I took a closer look at how NestWhileList reacts to having a maxim

I am using NestWhileList in a situation where it often hits the 'maximum number of evaluations'. After getting some curios results, I took a closer look at how NestWhileList reacts to having a maximum number of results specified:

Table[{nmax,
   Length@NestWhileList[
     (* f: nesting function *) Identity,
     (* initial state *) 1,
     (* test function *) False &,
     (* m: of arguments for test *) 1,
     (* nmax: max # applic开发者_如何转开发ations of f *) nmax,
     (* n: extra evaluations *) 1]}, {nmax, 0, 2}];
ToString[TableForm[%, 
  TableHeadings -> {None, {"nmax", "output length"}}]]

The surprising part is that nmax=1 is singled out: Here f is applied 2 times, while for all other values, it is only applied once:

 nmax   output length
 0      2
 1      3
 2      2

The 'extra evaluations' seem to be part of the problem. Leaving that option out gives much more reasonable results:

Table[{nmax,
  Length@NestWhileList[
    (* f: nesting function *) Identity,
    (* initial state *) 1,
    (* test function *) False&,
    (* m: of arguments for test *) 1,
    (* max: max # applications of f *) nmax]},{nmax,0,2}];
ToString[TableForm[%,TableHeadings->{None, {"nmax","output length"}}]]

Out[123]=    
   nmax   output length
   0      1
   1      1
   2      1

My question: does this somehow make sense, or is it just a bug?


It doesn't make sense, and I'm fairly sure it's just a bug. NestWhile is similarly afflicted:

In[53]:= NestWhileList[# + 1 &, 1, False &, 1, 1, 1]

Out[53]= {1, 2, 3}

In[54]:= NestWhile[# + 1 &, 1, False &, 1, 1, 1]

Out[54]= 3

Here's a workaround function for NestWhileList:

myNestWhileList[f_, expr_, test_, m_, max_, n_] :=
 Module[{nwl},
  nwl = NestWhileList[f, expr, test, m, max];
  Join[nwl, Rest[NestList[f, Last[nwl], n]]]
  ]

In[75]:= myNestWhileList[# + 1 &, 1, False &, 1, 1, 1]

Out[75]= {1, 2}

Clearly, It's not a completely general replacement for NestWhileList, but it should be easy enough to generalize if necessary.

I've submitted a bug report.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号