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: [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



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