MathGroup Archive 2011

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: NMinimize problem: fct minimized uses FindRoot

  • To: mathgroup at smc.vnet.net
  • Subject: [mg123628] Re: NMinimize problem: fct minimized uses FindRoot
  • From: Oliver Ruebenkoenig <ruebenko at wolfram.com>
  • Date: Tue, 13 Dec 2011 05:43:58 -0500 (EST)
  • Delivered-to: l-mathgroup@mail-archive0.wolfram.com
  • References: <201112121143.GAA12817@smc.vnet.net>


On Mon, 12 Dec 2011, Oleksandr Rasputinov wrote:

> On Sun, 11 Dec 2011 08:53:51 -0000, Doug Tinkham <dtinkham at live.ca> wrote:
>
>> Why never use Return?  As a C++ programmer, it is a habit.  I can't find
>> information saying why one should not. Is there a performance penalty?
>
> Return is not meant to be used in this way, although I wouldn't go as far
> as to say never to use it.
>
> The purpose of Return in Mathematica is to exit, returning a value, from
> an enclosing control structure, but specifically prior to the normal
> termination of that control flow or with a different value than would be
> yielded otherwise. For example, Do usually returns Null, but inserting
> Return into a Do loop can be used to obtain a non-Null return value.
>
> The problems with using Return in other contexts are that (a) if no
> enclosing control structure is found then the enclosing Return is not
> removed from the returned value; it will appear as Return[val], which is
> probably not what you want and (b) in deeply nested evaluations of the
> kind that are common in Mathematica, Return used incorrectly can incur a
> considerable performance penalty while walking back up the evaluation
> stack and trying to find a suitable enclosing control structure (which
> ultimately might be misidentified, possibly leading to erroneous results,
> or not exist at all, giving Return[val] where val was required).
>
> For example, the erroneous usage:
>
> Block[{a = 1, b = 2}, Return[a]; Return[b]]

You can "fix" this by using

Block[{a = 1, b = 2}, Return[a, Block]; Return[b]]

but Throw/Catch is probably a better bet.

Oliver

>
> gives:
>
> Return[1]
>
> but a correct usage:
>
> Do[Block[{a = 1, b = 2}, Return[a]; Return[b]], {1}]
>
> gives (because of the enclosing Do):
>
> 1
>
>



  • Prev by Date: Re: While Loop
  • Next by Date: Re: While Loop
  • Previous by thread: Re: NMinimize problem: fct minimized uses FindRoot
  • Next by thread: Re: NMinimize problem: fct minimized uses FindRoot