       index problem

• To: mathgroup at yoda.physics.unc.edu
• Subject: index problem
• From: rar at mail.physics.utah.edu (Rudolf A. Roemer)
• Date: Fri, 15 Apr 1994 10:22:23 -0700

```Dear MMA group:

I thought the enclosed example regarding the pitfalls of "indexed functions"
(MMA-Bible p.211) might interest some of you.

As you know, MMA allows for the definition of indexed heads such as the
following list

In:=
a  ={1., 1., 1.}
a  ={2., 2., 2.}

Out=
{1., 1., 1.}
{2., 2., 2.}

Let's now define a function that does nothing but sum over this list. Since
we use this function with both lists, we use "Bpar" to be our index.

In:=
trhoBE[x_,Bpar_]:=
Sum[
a[Bpar][[j]],
{j,1,Length[a[Bpar]]}
];

So, let's try this:

In:=
trhoBE[x,2]
trhoBE[x,N]

Out=
3.

Out=
2.

Oops, something went wrong, i.e., the index N was not accepted. This is
clear, since in our definition (In), we use the INTEGER "2" as the index
and not the REAL number "2.".

However, MMA sometimes does convert integers into reals apparently by
default as in the next example:

In:=
NIntegrate[trhoBE[x,1/2], {x,.1,.9}]
NIntegrate[trhoBE[x,N[1/2]], {x,.1,.9}]

Out=
0.4

Out=
0.4

Note that both answers are WRONG. We expect 3 * (0.9 - 0.1) = 2.4.
In a piece of complicated code, it is extremely hard to nail a problem
down to this. Only when we put the function trhoBE[] into the integration
by hand, do we get the right result (and N as index is wrong again,
although different from the above):

In:=
NIntegrate[
Sum[
a[[j]],
{j,1,Length[a]}
],
{x,.1,.9}
]
NIntegrate[
Sum[
a[N][[j]],
{j,1,Length[a[N]]}
],
{x,.1,.9}
]

Out=
2.4             (* YES, that's RIGHT! *)

Out=
1.6             (* WRONG again *)

Funny, isn't it?

-Rudo

###########################################################################
# Rudolf A. Roemer (RAR)         Room:   306 James Fletcher Building      #
# Department of Physics          Email:  rar at mail.physics.utah.edu        #
# University of Utah             FAX:    USA (801) 581 4801               #
# Salt Lake City, Utah 84112     Phone:  USA (801) 581 6424               #
# USA                                    USA (801) 461 4450 (home)        #
###########################################################################

```

• Prev by Date: Help in programming
• Next by Date: Re: ListContourPlot3D ?
• Previous by thread: Help in programming
• Next by thread: Re: index problem