Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.soft-sys.math.mathematica > #7143
| From | "Oleksandr Rasputinov" <oleksandr_rasputinov@hmamail.com> |
|---|---|
| Newsgroups | comp.soft-sys.math.mathematica |
| Subject | Re: NMinimize problem: fct minimized uses FindRoot |
| Date | 2011-12-12 11:46 +0000 |
| Organization | Steven M. Christensen and Associates, Inc and MathTensor, Inc. |
| Message-ID | <jc4pig$ck8$1@smc.vnet.net> (permalink) |
| References | <201112101227.HAA19219@smc.vnet.net> |
On Sun, 11 Dec 2011 08:53:51 -0000, Doug Tinkham <dtinkham@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
Back to comp.soft-sys.math.mathematica | Previous | Next | Find similar | Unroll thread
Re: NMinimize problem: fct minimized uses FindRoot "Oleksandr Rasputinov" <oleksandr_rasputinov@hmamail.com> - 2011-12-12 11:46 +0000
csiph-web