substitute sympy function with arbitrary arguments

前提是你 提交于 2019-12-12 11:57:09

问题


This should be an easy task, but I'm having a hard time getting it to work in Sympy. I want to substitute an undefined function with arbitrary arguments with a specific formula for example:

from sympy import *
var('a b c')
f= Function('f')
test= f(a+b)
lin= test.subs({f(c):2*(c)})
print(lin)

I want this to print out

2*(a+b)

However, for that I have to use

lin= test.subs({f(a+b):2*(a+b)})

Do I have to define f as a class in order to do this substitution?


回答1:


When you're doing advanced expression manipulation like this (okay, your example is still simple), the replace method is very useful:

test.replace(f, lambda arg: 2*arg)  # returns: 2*x + 2*y

From the docs:

[replace] Traverses an expression tree and performs replacement of matching subexpressions from the bottom to the top of the tree.

The 2nd example of the docs show that any function can be replaced by another that works on its arguments, as shown above for your example as well.



来源:https://stackoverflow.com/questions/27953715/substitute-sympy-function-with-arbitrary-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!