Wapiti
Wapiti

Reputation: 1911

Defining functions of symbols and other functions in sympy

I have a function f = sp.Function('f') and I have an expression that contains f, something like expr = 2*f + ... + f^2.

I want to do expr.subs(f, g). In other words, I want to replace f with another function g. I want to define g = x + y*h where x and y are type sp.Symbol and h is type sp.Function.

However, I cannot even define a function g of this kind:

import sympy as sp
x, y = sp.symbols('x, y')
g = x * y*sp.Function('h')

----> g = x * y*sp.Function('h')
TypeError: unsupported operand type(s) for *: 'Mul' and 'UndefinedFunction'

Upvotes: 0

Views: 1133

Answers (1)

Oscar Benjamin
Oscar Benjamin

Reputation: 14480

It's not clear to me exactly what you want. You can't literally used undefined functions as algebraic objects in SymPy but you can do essentially the same if you evaluate the function at a symbol. Maybe this helps to figure out your problem:

In [5]: f = Function('f')

In [6]: x = Symbol('x')

In [7]: expr = 1 + f(x)

In [8]: expr
Out[8]: f(x) + 1

In [9]: g = Lambda(x, sin(x)-1)

In [11]: g
Out[11]: x ↦ sin(x) - 1

In [10]: expr.subs(f, g)
Out[10]: sin(x)

Upvotes: 2

Related Questions