Ask Your Question

substitute variable inside function

asked 2020-04-10 18:53:00 +0200

Emil Widmann gravatar image

updated 2020-04-11 09:26:21 +0200

I can do

f(a,b) = a^2+b^3; f=f-f.subs(a=(a-1))
(a, b) |--> -(a - 1)^2 + a^2

I tried to write a function which does this for arbitrary expressions and variables

def test(self, symb):          
    return (self-self.subs(symb=(symb-1)))


(a, b) |--> 0

fails miserably. It seems self.subs(symb=(symb-1)) can not be evaluated properly. How can I achieve what I want?

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted

answered 2020-04-10 19:32:48 +0200

Juanjo gravatar image

updated 2020-04-10 19:34:01 +0200

Just double the equal sign in the substitution:

sage: f(a,b) = a^2+b^3
sage: def test(self, symb):          
....:     return (self-self.subs(symb==(symb-1)))
sage: test(f,a)
(a, b) |--> -(a - 1)^2 + a^2
edit flag offensive delete link more


great, thanks!

Emil Widmann gravatar imageEmil Widmann ( 2020-04-11 07:38:56 +0200 )edit

answered 2020-04-14 13:08:00 +0200

tmonteil gravatar image

Note that you can also use Python dicts instead of symbolic expressions, which is usually more robust for complex substitutions :

sage: def test(self, symb):          
....:     return self-self.subs({symb: symb-1})
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


Asked: 2020-04-10 18:53:00 +0200

Seen: 76 times

Last updated: Apr 14 '20