Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2014

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

Search the Archive

Re: How to avoid repeated recalculation of the same function

  • To: mathgroup at smc.vnet.net
  • Subject: [mg132673] Re: How to avoid repeated recalculation of the same function
  • From: Bill Rowe <readnews at sbcglobal.net>
  • Date: Sat, 3 May 2014 03:39:54 -0400 (EDT)
  • Delivered-to: l-mathgroup@mail-archive0.wolfram.com
  • Delivered-to: l-mathgroup@wolfram.com
  • Delivered-to: mathgroup-outx@smc.vnet.net
  • Delivered-to: mathgroup-newsendx@smc.vnet.net

On 5/2/14 at 2:18 AM, pgeipi10 at gmail.com wrote:

>I'm doing a calculaton that's purly symbolic (no graphing, numerical
>integration, etc.).

>Suppose I have a function f[x_]:=... that's very complex to build.
>In fact, f[x] ends up being a manageable expression (about 30
>characters) but it takes Mathematica about 30 min to build that
>expression.

>Another function g[] uses the function f[x] and references it many
>times. I've discovered that g[] actually builds f[x] every time it's
>referenced which takes 30 minutes each time. Theoretically,
>Mathematica could build it once and then use the resulting
>expression every time it's referenced.

>So how do I accomplish that? That is, how do I make it build f[x]
>once and then use the resulting expression when it's needed?

Use Set rather than SetDelayed in the definition of f[x]. For
example, consider

In[1]:= f[x_] := Integrate[2 z + 3, {z, 0, x}];
         g[x_] = Integrate[2 z + 3, {z, 0, x}];

Both accomplish the same thing as verified by

In[3]:= f[y] === g[y]
Out[3]= True

But notice the difference below

In[4]:= DownValues[g]
Out[4]= {HoldPattern[g[x_]] :> x^2 + 3*x}

In[5]:= DownValues[f]
Out[5]= {HoldPattern[f[x_]] :> Integrate[2*z + 3, {z, 0, x}]}

The integration step is done once with g but repeated every f is
called. And you can clearly see the difference this makes by
plotting both, i.e.,

In[6]:= Timing[Plot[f[x], {x, 0, 2}];]

Out[6]= {4.232786,Null}

In[7]:= Timing[Plot[g[x], {x, 0, 2}];]

Out[7]= {0.004068,Null}




  • Prev by Date: Re: How to avoid repeated recalculation of the same function
  • Next by Date: Re: How to avoid repeated recalculation of the same function
  • Previous by thread: Re: How to avoid repeated recalculation of the same function
  • Next by thread: Re: How to avoid repeated recalculation of the same function