First time here? Check out the FAQ!

Ask Your Question
0

Why won't sage math evaluate this expression?

asked 1 year ago

AndrewAndrew gravatar image

updated 1 year ago

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

Preview: (hide)

Comments

I just posted an answer to this at https://stackoverflow.com/questions/7....

John Palmieri gravatar imageJohn Palmieri ( 1 year ago )

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

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 1 year ago )

1 Answer

Sort by » oldest newest most voted
2

answered 1 year ago

Emmanuel Charpentier gravatar image

updated 1 year ago

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 β (a Python object defined by Sage), a symbolic variable u5 and a *symbolic variable u, then

  • sets Python variables :

    +beta pointing to beta,

    • u_5 pointing to u5, 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, u5 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 u5 are lost. Thr expression bound to p is *unchanged* : the pointers to beta and u5 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 u5 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,

Preview: (hide)
link

Your Answer

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

Add Answer

Question Tools

Stats

Asked: 1 year ago

Seen: 139 times

Last updated: Nov 10 '23