Re: check inside a loop?
- To: mathgroup at smc.vnet.net
- Subject: [mg80767] Re: check inside a loop?
- From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
- Date: Sat, 1 Sep 2007 00:26:37 -0400 (EDT)
- Organization: The Open University, Milton Keynes, UK
- References: <fb82ov$7ka$1@smc.twtelecom.net>
Jeremy Price wrote:
> I have a large loop that is ndsolving/nintegrating a bunch of things, and a
> lot of the results give me various errors due to the equations not being
> very nice. I'd like to have a way to check what values of my paramaters are
> causing the errors, but I can't find a way to do that inside a loop.
>
> For example, if I have something like,
> f[x_] = 1/Sin[2 pi x]
>
> For[ i=1, i < 1000, i++,
> f[i]
> ]
>
> I'm going to get a lot of "Power::infy: Infinite expression 1/0
> encountered." errors. I'd like to see what values of i these occur at.
It is possible that you are using a version prior 5.2, because none of
your examples, even with the typo for Pi fixed, succeed in producing an
error message.
In[1]:= f[x_] = 1/Sin[2 pi x]
For[i = 1, i < 1000, i++, f[i]]
Out[1]= Csc[2 pi x]
In[3]:= f[x_] = 1/Sin[2 Pi x]
For[i = 1, i < 1000, i++, f[i]]
Out[3]= Csc[2 \[Pi] x]
In[5]:= f[1]
Out[5]= ComplexInfinity
> I've tried something like
>
> For[ i=1, i<1000, i++,
> Check[ f[i] , i]
> ]
>
> But this just returns "Power::infy: Infinite expression 1/0 encountered."
> errors without the i vaule, which is different than I get by evaluating
> something like
> Check[ f[0],0]
> Which returns:
> Power::infy: Infinite expression 1/0 encountered.
> 0
>
> Is there any way I can get it to return the index that the error occured at
> for every error that occurs inside of the loop?
You can use any function as second argument for Check. For instance,
Print or Sow will do it:
In[1]:= g[n_] = 1/Mod[5, n]
Out[1]= 1/Mod[5, n]
In[2]:= For[i = 1, i < 10, i++,
Check[g[i], Print["Division by zero for i = ", i], Power::infy]]
During evaluation of In[2]:= Power::infy: Infinite expression 1/0 \
encountered. >>
During evaluation of In[2]:= Division by zero for i = 1
During evaluation of In[2]:= Power::infy: Infinite expression 1/0 \
encountered. >>
During evaluation of In[2]:= Division by zero for i = 5
In[3]:= Reap[
For[i = 1, i < 10, i++, Check[g[i], Sow[i], Power::infy]]][[2]]
During evaluation of In[3]:= Power::infy: Infinite expression 1/0 \
encountered. >>
During evaluation of In[3]:= Power::infy: Infinite expression 1/0 \
encountered. >>
Out[3]= {{1, 5}}
--
Jean-Marc