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: [mg132681] Re: How to avoid repeated recalculation of the same function
  • From: psycho_dad <s.nesseris at gmail.com>
  • Date: Sun, 4 May 2014 02:26:56 -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
  • References: <ljvdcg$bal$1@smc.vnet.net>

Hey!

Consider the behavior of the two functions f and f1 (I have added the Pause[2] to give the impression of a long calculation):

f[x_]:=(Pause[2];x^2)
f1[x_]:= f1[x]=(Pause[2];x^2)

(Notice the f1[x_]:= f1[x] "trick" used above...)

Now evaluate both of them:
f[x]
f1[x]

both take a long time to evaluate the first time. Now repeat:
f[x]
f1[x]

you will notice that f1[x] was done instantaneously! The reason is that Mathematica has included the value as part of the definition due to the f1[x_]:= f1[x] "trick", so it remembers it after it evaluates it once.

There are also other ways to do what you want, eg hardcoding by hand the result for f[x] after you evaluate it once (assuming it it always the same) etc.

Cheers




  • Prev by Date: 3D Plot Waterfall Plot how are should the Datastructure
  • Next by Date: Re: Version 9 export to PDF creates ridiculously large file
  • 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