I have a notebook which takes in a user-defined function and starting value and tracks the orbit of the particle under iteration of the function. The problem occurs when the user enters a starting value with an orbit that goes to infinity.


I get the error message:


How can I catch this?

  • 1
    $\begingroup$ Look up Check[]. $\endgroup$ – J. M.'s technical difficulties Jun 17 '13 at 18:28
  • $\begingroup$ It would be nice to have more details about what you are doing. If you're iterating a polynomial, for example, there's a simple bound on the absolute value of the iterate, beyond which, you are guaranteed the orbit will diverge to Infinity. It's easy to incorporate this into a loop or a NestWhileList. One issue with Check is that the Overflow[] won't be detected until after it happens. That's way too late, if you're working with compiled code. $\endgroup$ – Mark McClure Jun 17 '13 at 18:41

It depends on how you are doing the iteration. For example, if you were using Nest, then it could be replaced by NestWhile. If you are willing to modify the function, the you can explicitly test for divergence in the function, for instance

  f[x_] := Clip[x^2, {-1000, 1000}]

will bound f. If it is a user defined function, then you can wrap it in the Clip or define it using Piecewise:

f[x_] := Piecewise[{{x^2, Abs[x] < 1000}, {1000, x >= 1000}, {-1000, x <= 1000}}]

Again, you might place the user-defined function in the first position and have the upper and lower limits always be fixed to catch the divergence. Perhaps more elegant is to use a conditional function definition:

f[x_] := x^2;
f[x_ /; x > 1000] := 1000
f[x_ /; x < -1000] := -1000

In this case, you can have the user define the function as before, but you also have the explicit divergence criteria predefined. Of course you might use more sensible numbers than "+/-1000"!

| improve this answer | |
  • $\begingroup$ Thank-you! I've got some code to clean up. $\endgroup$ – twhoward99 Jun 17 '13 at 18:52
  • 1
    $\begingroup$ +1, especially for the conditional function definition approach. $\endgroup$ – Jagra Jun 17 '13 at 20:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.