# Why won't sage math evaluate this expression?

EDIT : reformatted code

var('u_5 u beta')
y = u - u_5 + beta*(exp(u)-u-4)
beta = 1.0
u_5 = -4.0
p = y.subs(u==u_5)
p


results in: 0.0183156388887342*beta - u_5 - 4.00000000000000

How can I get a numerical value? I did try numerical_approx, n() etc.

I expect it to multiply 0.0183... by 1 (beta) and subtract the -4 for u_5

edit retag close merge delete

I allowed myself to reformat your code in order to make it readable.

Sort by » oldest newest most voted

John is right. I'll paraphrase his answer for the benefit of future users.

Let's dissect this :

var('u_5 u beta')


This is equivalent to u_5, u, beta)=SR.var("u_5 u beta). In particular, this

• create a symbolic variable $\beta$ (a Python object defined by Sage), a symbolic variable $u_5$ and a *symbolic variable $u$, then

• sets Python variables :

+beta pointing to $beta$,

• u_5 pointing to $u_5$, and

• u pointing to $u$.

y = u - u_5 + beta*(exp(u)-u-4)

This create a symbolic expression, a Python structure defuined by Sage, containing, among others, pointers to $beta$, $u_5$ and $u$.

beta = 1.0
u_5 = -4.0


This binds the Python varables beta and u_5 to the numerical values 1.0 and -4 respectively. The links to $beta$ and $u_5$ are lost. Thr expression bound to p is *unchanged* : the pointers to $beta$ and $u_5$ still point to the respective symbolic variables.

p = y.subs(u==u_5)


This create a new symbolic expression where the pointer to $u$ us replaced by the value of the Python variable u_5, which is now the numeric value -4.0. The pointers to $beta$ and $u_5$ are unmodified.

p


This prints the new symbolic expression, which still contains (pointers to) symbolic variables.what you wnt to do is probably :

sage: y.subs(u==u_5).subs([beta==1, u_5==-4])
e^(-4)


or, more probably :

sage: y.subs(u==u_5).subs([beta==1, u_5==-4]).n()
0.0183156388887342


This can be abbreviated as :

sage: y.subs(u==u_5)(beta=1, u_5=-4).n()
0.0183156388887342


See the documentation for details, and the initial chapters of this marvelous book, which I cannot recommend too much.

Note that :

sage: y.subs([u==u_5, beta==1, u_5==-4])
e^u_5


in which the substitutions are executed in a different order, resulting in a different value.

HTH,

more