Ask Your Question
0

substitute variable inside function

asked 2020-04-10 11:53:00 -0500

Emil Widmann gravatar image

updated 2020-04-11 02:26:21 -0500

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)))

but

test(f,a)
(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
1

answered 2020-04-10 12:32:48 -0500

Juanjo gravatar image

updated 2020-04-10 12:34:01 -0500

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

Comments

great, thanks!

Emil Widmann gravatar imageEmil Widmann ( 2020-04-11 00:38:56 -0500 )edit
1

answered 2020-04-14 06:08:00 -0500

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

Stats

Asked: 2020-04-10 11:53:00 -0500

Seen: 54 times

Last updated: Apr 14