How to define a mathematical function in SymPy?

Robin picture Robin · May 8, 2016 · Viewed 23.5k times · Source

I've been trying this now for hours. I think I don't understand a basic concept, that's why I couldn't answer this question to myself so far.

What I'm trying is to implement a simple mathematical function, like this:

f(x) = x**2 + 1

After that I want to derive that function.

I've defined the symbol and function with:

x = sympy.Symbol('x')
f = sympy.Function('f')(x)

Now I'm struggling with defining the equation to this function f(x). Something like f.exp("x**2 + 1") is not working.

I also wonder how I could get a print out to the console of this function after it's finally defined.

Answer

asmeurer picture asmeurer · May 9, 2016

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)