Ask Your Question
0

substitute variable inside function

asked 4 years ago

Emil Widmann gravatar image

updated 4 years ago

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?

Preview: (hide)

2 Answers

Sort by » oldest newest most voted
1

answered 4 years ago

Juanjo gravatar image

updated 4 years ago

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
Preview: (hide)
link

Comments

great, thanks!

Emil Widmann gravatar imageEmil Widmann ( 4 years ago )
1

answered 4 years ago

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})
Preview: (hide)
link

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: 4 years ago

Seen: 299 times

Last updated: Apr 14 '20