TimeConstrained and returning a partial answer
- To: mathgroup at smc.vnet.net
- Subject: [mg88200] TimeConstrained and returning a partial answer
- From: Szabolcs Horvát <szhorvat at gmail.com>
- Date: Mon, 28 Apr 2008 04:38:30 -0400 (EDT)
- Organization: University of Bergen
The following came up on sci.math.symbolic: Among the examples on the doc page of TimeConstrained there is one where a partial (less precise) answer is returned even if the calculation cannot be finished within the time constraint. I was wondering if there is a way to create user-defined functions with this behaviour. I found two relevant functions in the docs: AbortProtect and CheckAbort. Here's a small test program: AbortProtect@CheckAbort[ x = 0; Do[Pause[.1]; x++, {100}]; x, x] This program will return an answer even if the calculation is aborted with Alt+. (or the menu item Evaluation -> Abort evaluation). Now let us try to use it with TimeConstrained: TimeConstrained[ AbortProtect@CheckAbort[ x = 0; Do[Pause[.1]; x++, {100}]; x, x], 1 ] // AbsoluteTiming Unfortunately this always runs for 10 full seconds, and then returns $Aborted (i.e. the worst possible thing happens: the calculation is not stopped after 1 sec, but no answer is returned.) ** Question: How can this program be modified so that TimeConstrained will be able to stop it after 1 sec, and it will still return an answer? Note: I experimented a little with the example from the docs, and I cannot reproduce the result that is presented there. If the calculation cannot be finished within the time constraint, $Aborted is returned: In[1]:= Timing[NDSolve[{Derivative[2][x][t] + x[t] == 0, x[0] == 1, Derivative[1][x][0] == 0}, x, {t, 0, 50000*Pi}, MaxSteps -> Infinity]] Out[1]= {5.578, {{x -> InterpolatingFunction[]}}} In[2]:= AbsoluteTiming[TimeConstrained[ NDSolve[{Derivative[2][x][t] + x[t] == 0, x[0] == 1, Derivative[1][x][0] == 0}, x, {t, 0, 50000*Pi}, MaxSteps -> Infinity], 5]] Out[2]= {5.0625`8.155910029718697, $Aborted} In[3]:= AbsoluteTiming[TimeConstrained[ NDSolve[{Derivative[2][x][t] + x[t] == 0, x[0] == 1, Derivative[1][x][0] == 0}, x, {t, 0, 50000*Pi}, MaxSteps -> Infinity], 6]] Out[3]= {5.984375`8.228563793480708, {{x -> InterpolatingFunction[]}}}