[Date Index]
[Thread Index]
[Author Index]
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[25]:=
a[2] ={1., 1., 1.}
a[1] ={2., 2., 2.}
Out[25]=
{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[26]:=
trhoBE[x_,Bpar_]:=
Sum[
a[Bpar][[j]],
{j,1,Length[a[Bpar]]}
];
So, let's try this:
In[27]:=
trhoBE[x,2]
trhoBE[x,N[2]]
Out[27]=
3.
Out[28]=
2.
Oops, something went wrong, i.e., the index N[2] was not accepted. This is
clear, since in our definition (In[25]), 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[29]:=
NIntegrate[trhoBE[x,1/2], {x,.1,.9}]
NIntegrate[trhoBE[x,N[1/2]], {x,.1,.9}]
Out[29]=
0.4
Out[30]=
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[2] as index is wrong again,
although different from the above):
In[31]:=
NIntegrate[
Sum[
a[2][[j]],
{j,1,Length[a[2]]}
],
{x,.1,.9}
]
NIntegrate[
Sum[
a[N[2]][[j]],
{j,1,Length[a[N[2]]]}
],
{x,.1,.9}
]
Out[31]=
2.4 (* YES, that's RIGHT! *)
Out[32]=
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**
| |