Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

python - How to define a mathematical function in SymPy?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...