Mathematica 9 is now available
Services & Resources / Wolfram Forums
MathGroup Archive
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2005

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

Search the Archive

Re: Speeding up simple Mathematica expressions?

  • To: mathgroup at
  • Subject: [mg63249] Re: Speeding up simple Mathematica expressions?
  • From: Jon Harrop <usenet at>
  • Date: Tue, 20 Dec 2005 23:35:34 -0500 (EST)
  • References: <do8ioc$rvd$>
  • Sender: owner-wri-mathgroup at

AES wrote:
> I'd appreciate some practical advice on speeding up some simple function
> evaluations.
> I'm evaluating a series of functions of which a typical example is
>   f[a_, x_] := Sum[
>                     Exp[-(Pi a)^2 n^2 -
>                              ((x - n Sqrt[1 -  (Pi^2 a^4)])/a)^2],
>                     {n, -Infinity, Infinity}];
> (The function is essentially a set of narrow gaussian peaks located at x
> ? n Sqrt[1 - (Pi a^2)^2] ? n , with the peak amplitudes dropping off
> rapidly with increasing x.)
> Despite being a fairly simple function, this evaluates very slowly on my
> iBook G4 -- takes a long time to make a plot of say  f[0.1, x] for  0 <
> x < 3.  What can or should I do to speed this up?

Good question. The time seems to be spent symbolically evaluating the sum
only to find that it cannot be reduced. You can avoid this overhead by
evading evaluation using Hold.

Here's the original:

In[1]:= f[a_, x_] :=
  N@Sum[Exp[-(Pi a)^2 n^2 - ((x - n Sqrt[1 - (Pi^2 a^4)])/
                a)^2], {n, -Infinity, Infinity}]

In[2]:= Timing[f[3., 3.]] // InputForm

Out[2]//InputForm= {1.28*Second, 1.9555359833625323 + 0.*I}

In[3]:= Timing[f[3., 3.]] // InputForm

Out[3]//InputForm= {0.14999999999999988*Second, 1.9555359833625323 + 0.*I}

and here's an optimised version that is >15x faster:

In[4]:= g[a_, x_] :=
        Sum[Exp[-(Pi a)^2 n^2 - ((x - n Sqrt[1 - (Pi^2 a^4)])/
                    a)^2], {n, -Infinity, Infinity}]                   

In[5]:= Timing[g[3., 3.]] // InputForm

Out[5]//InputForm= {0.009999999999999985*Second, 1.9555359833623651 + 0.*I}

In[6]:= Timing[g[3., 3.]] // InputForm

Out[6]//InputForm= {0.*Second, 1.9555359833623651 + 0.*I}

Note that the answer is slightly different. I'm not sure why...

Dr Jon D Harrop, Flying Frog Consultancy Ltd.

  • Prev by Date: Re: Re: Replacement equivalence?
  • Next by Date: Re: Speeding up simple Mathematica expressions?
  • Previous by thread: Re: "Alternating" function
  • Next by thread: Re: Speeding up simple Mathematica expressions?