Ask Your Question
2

Substitution of free variable

asked 2019-09-10 12:23:14 -0500

Jean-Sébastien gravatar image

I have sagecells on a page that are used to solve some equations. In a further cell, I want to substitute a given value in place of a free variable. Sage's free variables have names such as r1, r2 etc.

Is there a way (some kind of wildcard) to substitute a value for a free variable without knowing its name? I'd like this because depending on the order of execution a user would press the cells, the names would change.

It would look like this

CELL1

sol1=solve([x+y==1],x,y)

CELL2

sol2=solve([x-y==3],x,y)

and then further down I would like a new cell that would substitute the free variable in sol1 to a given value, say 0.

However if I use something along the line of

sol1part=sol1.substitute(r1=0) and the user executed for some reason cell2 before cell1, it will not work.

edit retag flag offensive close merge delete

2 answers

Sort by » oldest newest most voted
1

answered 2019-09-10 12:39:35 -0500

tmonteil gravatar image

updated 2019-09-10 12:42:37 -0500

If you are sure that there is only one free variable, then you can easily identify it.

First, use solution_dict option to deal with the result more easily:

sage: sol1 = solve([x+y==1], x, y, solution_dict=True)
sage: sol1
[{y: r3, x: -r3 + 1}]

Now, you can ask for the variables appearing in a symbolic expression, see:

sage: sol1[0][x]
-r3 + 1
sage: sol1[0][x].variables()[0]

So, you can give it a Python name and use it afterwards:

sage: freevar = sol1[0][x].variables()[0]
sage: expr = sol1[0][x]
sage: expr
-r3 + 1
sage: expr.subs({freevar:10})
-9
edit flag offensive delete link more

Comments

This should work. I think I should be able to adapt it if there are more than 1 free variable as well

Jean-Sébastien gravatar imageJean-Sébastien ( 2019-09-10 12:55:05 -0500 )edit

Yes, but you might have to do some assumption on their order i guess.

tmonteil gravatar imagetmonteil ( 2019-09-10 13:06:06 -0500 )edit
0

answered 2019-09-10 15:05:57 -0500

Emmanuel Charpentier gravatar image

You might collect all the variables from your solutions, and inject those whose string representation does not appear in show_identifiers() in the global namespace (see sage.misc.misc.inject_variable?), or simply declare them with var.

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

1 follower

Stats

Asked: 2019-09-10 12:23:14 -0500

Seen: 25 times

Last updated: Sep 10