2010-11-08 63 views
7

我在使用NestWhileList时经常遇到'最大数量的评估'。得到了一些古玩结果后,我把如何NestWhileList反应的仔细看看不具有所指定的最大结果数:Mathematica:Grokking'NestWhileList`的最大评估数量参数

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

令人惊讶的是,nmax=1是单挑:这里f应用的2倍,而所有其他值,它只应用一次:

nmax output length 
0  2 
1  3 
2  2 

'额外评估'似乎是问题的一部分。离开那个选项给出了更加合理的结果:

Table[{nmax, 
    [email protected][ 
    (* 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 

我的问题:这是否在某种程度上意义,还是仅仅是一个错误吗?

回答

4

它没有任何意义,我相当确信它只是一个错误。 NestWhile同样困扰:

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 

下面是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} 

显然,它不是为NestWhileList一个完全通用的替代品,但它应该是很容易一概而论,如果必要的。

我已经提交缺陷报告。

+0

谢谢迈克尔 - 想通了这只是最简单的方法:) – Janus 2010-11-08 06:48:58

+1

没问题,并感谢您指出。如果您愿意,您也可以将错误邮件发送到[email protected]。 – 2010-11-08 06:59:34