MathGroup Archive 2002

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

Search the Archive

Re: Slow iteration in a functional program

  • To: mathgroup at smc.vnet.net
  • Subject: [mg35650] Re: [mg35630] Slow iteration in a functional program
  • From: Sseziwa Mukasa <mukasa at jeol.com>
  • Date: Wed, 24 Jul 2002 02:06:21 -0400 (EDT)
  • Sender: owner-wri-mathgroup at wolfram.com

On Tuesday, July 23, 2002, at 01:51 AM, Matthew Rosen wrote:

> Everyone,
>   I've been trying to recast an iterative calculation I do as a
> procedural program in C as an elegant functional program in
> Mathematica 4.1. The Mathematica code is much more transparent, but
> the resultant execution time is more than two orders of magnitude
> longer. Any suggestions would be greatly appreciated.The following is
> a schematic of the problem.
>
>
> There are three equations in the iteration variable, n:
>
>    G[n_] := ListIntegrate[xsec Phi[n]]      Both xsec and Phi[n] are
> 400 points long.
>
>    P[n_] := G[n]/(G[n]+(a constant)+D[n])   D[n] is a simple algebraic
> function of n.
>
>    Phi[1] = Flux;                             Flux is 400 points long.
>    Phi{n_] := Phi[n-1] Exp[-(1-P[n-1])*xsec
>
>
> The goal is to evaluate P[n_] for an n around 1000. After running, I
> need to know all the values of P[n] and Phi[n] at each n from 1 to
> nmax. Note, P[n] is a number and Phi[n] is 400 points long.
>
> Currently,
>
> Timing[P[1]] = 0.1 s
> Timing[P[2]] = 0.2 s
> Timing[P[5]] = 8.4 s.
>
> I dont dare try to evaluate P[1000] as I need to do. Every time I
> evaluate these functions they recalculate from scratch. I think I
> need to somehow tell Mathematica to save the intermediate values.
> Curious is that the calculation time is going up like n^2, not like n
> as I would have thought. The equivalent procedural c-code runs in
> less than 1 second to evaluate P[1000].
>
> Thanks in advance for any guidance!
>
>

You may want to cache your values, especially since none of the lists 
are very long.  Try defining P as P[n_]:=P[n]=G[n]/(G[n]+...) and 
Phi[n_] as Phi[n_]:=Phi[n]=Phi[n-1] Exp[-(1-P[n-1])*xsec].  For that 
matter you may want to do the same thing with G.  Doing this for a 
simplified version of your system (constant = 1, D[n_]:=n^2 etc.) I get 
the following timings

(Dialog) In[153]:=
Timing[P[1];]
Timing[P[2];]
Timing[P[5];]

(Dialog) Out[153]=
{0.02 Second,Null}

(Dialog) Out[154]=
{0.03 Second,Null}

(Dialog) Out[155]=
{0.07 Second,Null}

Regards,

Ssezi



  • Prev by Date: RE: Re: Q: Simplify with "much less" assumptions
  • Next by Date: Re: Slow iteration in a functional program
  • Previous by thread: RE: Slow iteration in a functional program
  • Next by thread: Re: Slow iteration in a functional program