Ask Your Question

Why won't sage math evaluate this expression?

asked 2023-11-09 18:54:50 +0100

updated 2023-11-10 08:25:36 +0100

Emmanuel Charpentier gravatar image

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)

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 flag offensive close merge delete


I just posted an answer to this at

John Palmieri gravatar imageJohn Palmieri ( 2023-11-09 19:58:15 +0100 )edit

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

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 2023-11-10 08:26:29 +0100 )edit

1 Answer

Sort by ยป oldest newest most voted

answered 2023-11-10 09:06:35 +0100

Emmanuel Charpentier gravatar image

updated 2023-11-10 09:09:43 +0100

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.


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])

or, more probably :

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

This can be abbreviated as :

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

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])

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


edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2023-11-09 18:54:50 +0100

Seen: 50 times

Last updated: Nov 10 '23