We have already covered expression trees derived from fast callable objects,
but a fast callable object is just one representation that is geared for
evaluation in hardware arithmetic.
In this lecture we examine how expressions in Sage are stored internally.
Note that we fixed the seed of the random number generator,
so we will always see the same polynomial printed.
x*y^2*z^4+1/5*x^5*y+2*x*y^2*z^2+x^3
Unfortunately, the methods operands() and operator()
do not work on a multivariate polynomial of this type.
We convert p to a general SageMath expression
by evaluation in new symbolic variables.
Because we will not use the polynomial ring R anymore,
we choose the same letters x, y, and z for the new variables.
Then we see that sq has the same value as p,
but is of type sage.symbolic.expression.Expression.
We can then ask to see the operands and the operators.
print(sq.operands())print(sq.operator())
What is printed is
[x*y^2*z^4,1/5*x^5*y,2*x*y^2*z^2,x^3]
and
<functionadd_varargat0x1192011b8>.
Observe that the list of operands has four elements
and that the operator is add_vararg, an addition
with a variable number of arguments.
Therefore:
expression trees of general Sage expressions are NOT binary.
We start drawing the expression tree in a top down fashion.
All the operators are multiplication,
except for the last operator.
Because the operands will be used as labels in the new expression tree,
we convert to strings.
Apparently there is no way to substitute nodes in a tree.
We will manually replace the appropriate entries in the list of leaves
and redefine the expression tree.
The data structure which represents a fast callable object
corresponds to a binary tree.
In a binary tree, every internal node (that is not a leaf)
has exactly two children.
One reason why fast callable objects are fast is
because they are limited to numerical values.
The elementary numerical operations such as addition,
multiplication, exponentiation are all binary operations and therefore,
the expression tree defined by a fast callable object is a binary tree.
Consider p=3*x^4-6*x^3+5*x^2+9*x-7.
Draw the expression tree for p.
Also give all Sage commands with their output used to make your drawing.
Consider p=3*x^4-6*x^3+5*x^2+9*x-7.
Compute the Horner form q for p
and draw the expression tree for q.
Also give all Sage commands with their output used to make your drawing.
Consider p=3*x^4-6*x^3+5*x^2+9*x-7
and its evaluation at math.pi.
Compare with timeit the efficiency of the original expression,
the Horner q form of p, and the fast callable objects
of p and q.
Consider the expression:
\[x + \frac{y}{x^2 - y + 1}.\]
Draw the internal representation of this expression.