How to substitute a list of equalities into a formula?

82 views
Skip to first unread message

ancienthart

unread,
Apr 8, 2012, 2:34:05 AM4/8/12
to sage-s...@googlegroups.com
Hi guys,
Some current code I'm playing around with:

f(x,y) = (1-x)^2 + 100*(y - x^2)^2

solve([f.diff(ar) for ar in f.args()],f.args())[0]

Gives me a list of solutions as:
[x=1;y=1]

Is there any way to programatically substitute this list of equalities back into f?

Joal Heagney

P Purkayastha

unread,
Apr 8, 2012, 3:33:20 AM4/8/12
to sage-s...@googlegroups.com
Something like this?

sage: solns = solve([f.diff(ar) for ar in f.args()],f.args(), solution_dict=True)[0]
sage: f( *(solns[ar] for ar in f.args()) )
0

Michael Orlitzky

unread,
Apr 9, 2012, 1:39:49 AM4/9/12
to sage-s...@googlegroups.com
On 04/08/2012 03:33 AM, P Purkayastha wrote:
> Something like this?
>
> sage: solns = solve([f.diff(ar) for ar in f.args()],f.args(),
> solution_dict=True)[0]
> sage: f( *(solns[ar] for ar in f.args()) )
> 0

The `subs_expr` method accepts multiple equations already, so you can
shave a few characters off that:

sage: solution = solve([f.diff(ar) for ar in f.args()],f.args())[0]
sage: f(x,y).subs_expr(*solution)
0

ancienthart

unread,
Apr 9, 2012, 10:18:12 PM4/9/12
to sage-s...@googlegroups.com
Hah. Thanks Michael and P. I first learnt Python in the 1.5 era, so there's a few of the nice new syntax features I'm still not up to speed on.
Any reason why .subs doesn't accept multiple arguments? Would there be any point in requesting .subs_expr become the new default on trac?

Joal Heagney

Michael Orlitzky

unread,
Apr 10, 2012, 1:11:03 PM4/10/12
to sage-s...@googlegroups.com
On 04/09/12 22:18, ancienthart wrote:
> Hah. Thanks Michael and P. I first learnt Python in the 1.5 era, so
> there's a few of the nice new syntax features I'm still not up to speed on.
> Any reason why .subs doesn't accept multiple arguments? Would there be
> any point in requesting .subs_expr become the new default on trac?

`subs` accepts multiple arguments too, and will generally work like a
function call with named arguments if you want it to.

sage: x,y,z = var('x,y,z')
sage: f = x + y + z
sage: f(x=1, y=2, z=3)
6
sage: f.subs(x=1, y=2, z=3)
6
sage: f.subs({x: 1, y: 2, z: 3})
6

Passing it one equation does work,

sage: f.subs(x == 1)
y + z + 1

But more than one doesn't,

sage: f.subs(x == 1, y == 2)
...
TypeError: substitute() takes at most 1 positional argument (2 given)

I guess all that's missing is the ability to pass it multiple equations,
like `subs_expr`. It would probably be easy to add that ability to
`subs` if you want to create a ticket for something.

ancienthart

unread,
Apr 12, 2012, 9:04:17 AM4/12/12
to sage-s...@googlegroups.com
Reply all
Reply to author
Forward
0 new messages