MathGroup Archive 2012

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

Search the Archive

Re: Functions That Remember Values They Have Found

  • To: mathgroup at smc.vnet.net
  • Subject: [mg127610] Re: Functions That Remember Values They Have Found
  • From: Bob Hanlon <hanlonr357 at gmail.com>
  • Date: Tue, 7 Aug 2012 03:02:06 -0400 (EDT)
  • Delivered-to: l-mathgroup@mail-archive0.wolfram.com
  • Delivered-to: l-mathgroup@wolfram.com
  • Delivered-to: mathgroup-newout@smc.vnet.net
  • Delivered-to: mathgroup-newsend@smc.vnet.net
  • References: <20120806083728.AC1FE683B@smc.vnet.net>

Clear[Hgeom, Hgeom2, Hgeom3]

Hgeom[n_] := H[n] = Sum[
    (1 - 0.5)^i/(1 - 0.5^i) Hgeom[n - i],
    {i, 1, n}]/n
Hgeom[0] = 1;

Hgeom[4]

0.203175

The memory is not effective when stored under a separate name

?? Hgeom

Use the same function name for the memory

Hgeom2[n_Integer] := Hgeom2[n] =
   Sum[(1 - 0.5)^i/(1 - 0.5^i)
       Hgeom2[n - i], {i, 1, n}]/n;
Hgeom2[0] = 1;

Hgeom2[4]

0.203175

?? Hgeom2

You could also use exact values

Hgeom3[n_Integer] := Hgeom3[n] =
   Sum[2^-i/(1 - 2^-i)
       Hgeom3[n - i], {i, 1, n}]/n;
Hgeom3[0] = 1;

Hgeom3[4]

64/315

?? Hgeom3

Note the timing differences

m = 18;

{Timing[Hgeom[m];][[1]],
 Timing[Hgeom2[m];][[1]],
 Timing[Hgeom3[m];][[1]]}

{3.09407, 0.001196, 0.002241}

Demonstrating that the results are equal

And @@ Table[
  Hgeom[n] == Hgeom2[n] == Hgeom3[n],
  {n, 0, m}]

True


Bob Hanlon


On Mon, Aug 6, 2012 at 4:37 AM, Esteban Gonz=E1lez Morales
<yo8231 at gmail.com> wrote:
> Hi, I was trying to create a recursive function and I read the help about=
 it, and wrote this code
>
> Hgeom[n_] :=
>  H[n] = Sum[(1 - 0.5)^i/(1 - 0.5^i) Hgeom[n - i], {i, 1, n}]/n
> Hgeom[0] = 1;
>
> However, when I calculate Hgeom[10] it gives me the right value, and then=
 I ask for the information about Hgeom and get that it has values calculate=
d.
>
> Have you any idea what could have gone wrong?
>



  • Prev by Date: problem in solving inconsistent system of equations
  • Next by Date: Re: Functions That Remember Values They Have Found
  • Previous by thread: Functions That Remember Values They Have Found
  • Next by thread: Re: Functions That Remember Values They Have Found