MathGroup Archive 2005

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

Search the Archive

Re: Speeding up simple Mathematica expressions?

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

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_] :=
  ReleaseHold@
    N@HoldForm@
        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.
http://www.ffconsultancy.com/products/ocaml_for_scientists/chapter1.html


  • 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?