Re: NMinimize problem: fct minimized uses FindRoot
- To: mathgroup at smc.vnet.net
- Subject: [mg123586] Re: NMinimize problem: fct minimized uses FindRoot
- From: "Oleksandr Rasputinov" <oleksandr_rasputinov at hmamail.com>
- Date: Mon, 12 Dec 2011 06:43:17 -0500 (EST)
- Delivered-to: l-mathgroup@mail-archive0.wolfram.com
- References: <201112101227.HAA19219@smc.vnet.net>
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]]
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
- Follow-Ups:
- Re: NMinimize problem: fct minimized uses FindRoot
- From: Oliver Ruebenkoenig <ruebenko@wolfram.com>
- Re: NMinimize problem: fct minimized uses FindRoot
- From: Andrzej Kozlowski <akoz@mimuw.edu.pl>
- Re: NMinimize problem: fct minimized uses FindRoot
- References:
- NMinimize problem: fct minimized uses FindRoot
- From: "Doug Tinkham" <dtinkham@live.ca>
- NMinimize problem: fct minimized uses FindRoot