How to define a mathematical function in SymPy?

Here's your solution:

>>> import sympy
>>> x = sympy.symbols('x')
>>> f = x**2 + 1
>>> sympy.diff(f, x)
2*x

sympy.Function is for undefined functions. Like if f = Function('f') then f(x) remains unevaluated in expressions.

If you want an actual function (like if you do f(1) it evaluates x**2 + 1 at x=1, you can use a Python function

def f(x):
    return x**2 + 1

Then f(Symbol('x')) will give a symbolic x**2 + 1 and f(1) will give 2.

Or you can assign the expression to a variable

f = x**2 + 1

and use that. If you want to substitute x for a value, use subs, like

f.subs(x, 1)

Another possibility (isympy command prompt):

>>> type(x)
<class 'sympy.core.symbol.Symbol'>
>>> f = Lambda(x, x**2)
>>> f
     2
x ↦ x 
>>> f(3)
9

Calculating the derivative works like that:

>>> g = Lambda(x, diff(f(x), x))
>>> g
x ↦ 2x
>>> g(3)
6

Tags:

Python

Sympy