2010-11-08 61 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