Ask Your Question
2

Substitution of free variable

asked 2019-09-10 19:23:14 +0100

Jean-Sébastien gravatar image

updated 2020-08-07 13:03:41 +0100

slelievre 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 19:39:35 +0100

tmonteil gravatar image

updated 2019-09-10 19:42:37 +0100

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 19:55:05 +0100 )edit

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

tmonteil gravatar imagetmonteil ( 2019-09-10 20:06:06 +0100 )edit
0

answered 2019-09-10 22:05:57 +0100

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 19:23:14 +0100

Seen: 1,156 times

Last updated: Aug 07 '20