# Substitution of free variable

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

Sort by » oldest newest most voted

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[x]
-r3 + 1
sage: sol1[x].variables()


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

sage: freevar = sol1[x].variables()
sage: expr = sol1[x]
sage: expr
-r3 + 1
sage: expr.subs({freevar:10})
-9

more

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

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

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.

more