如何在 SymPy 中定义数学函数? [英] How to define a mathematical function in SymPy?

查看:31
本文介绍了如何在 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)

现在我正在努力定义这个函数f(x)的方程.f.exp("x**2 + 1") 之类的东西不起作用.

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.

推荐答案

sympy.Function 用于未定义的函数.就像如果 f = Function('f') 那么 f(x) 在表达式中保持未计算.

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

如果你想要一个实际的函数(比如如果你做 f(1) 它会在 x=1 计算 x**2 + 1>,你可以使用一个Python函数

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

然后 f(Symbol('x')) 将给出一个符号 x**2 + 1 并且 f(1) 将给 2.

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

并使用它.如果你想用 x 代替一个值,使用 subs,比如

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

f.subs(x, 1)

这篇关于如何在 SymPy 中定义数学函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆