How do you interpret negative levels in Mathematica?
I am t开发者_如何学Pythonrying to gain a deeper understanding of how Mathematica expressions are represented internally, and am puzzled by the logic of the Level
command in Mathematica. If we have the following input:
In[1]:= a = z*Sin[x + y] + z1*Cos[x1 + y1]
Out[1]= z1 Cos[x1 + y1] + z Sin[x + y]
In[2]:= FullForm[a]
Out[2]= Plus[Times[z1,Cos[Plus[x1,y1]]],Times[z,Sin[Plus[x,y]]]]
In[3]:= TreeForm[a]
We get the following tree:
If we ask Mathematica to return Level 4 only, we get:
In[4]:= Level[a,{4}]
Out[4]= {x1,y1,x,y}
I understand that we are 4 levels down from the "stem" (the Plus operator at Level 0). In fact, I think I understand that positive indexes are always in relation to the stem position of the tree. (I hope I'm correct about that??)
In contrast, when you ask for a negative level, there is no common reference point (like the stem above), because different branches of the tree are of varying lengths. So, if you ask Mathematica to provide only Level -1, we get:
In[6]:= Level[a,{-1}]
Out[6]= {z1,x1,y1,z,x,y}
I was surprised by this output, when I had guessed that I should get back {x1, y1, x, y}
(without z1
& z
). But ok, if I try to understand this, I take -1 to mean "the end of each branch". If this is so, then I would expect Level[a,{-2}]
to return:
{z1*Cos[x1+y1],z*Sin[x+y],x1+y1,x+y}
But, this is not what I get back, Mathematica yields:
In[8]:= Level[a,{-2}]
Out[8]= {x1+y1,x+y}
So, now I am confused, and don't see a consistent way of understanding the output of negative levels.
Is there a consistent, easier way of understanding this topic? Is there a certain "correct" way I should be reading the structure of the tree?
Sorry for the "long-winded question", but I hope you understand what I am asking.
If you look at the docs, they say:
A negative level -n consists of all parts of expr with depth n.
So negative levels are not counted from a reference point, but are defined based on the depth of subexpressions. z1*Cos[x1+y1]
is of depth 4, so it's not returned when you ask for Level[..., {-2}]
.
精彩评论