input a symbolic function in a python code

我的未来我决定 提交于 2019-12-06 02:41:10
mirk

If you need good support for symbolic funcions, you should consider using sage.

It is a preprocessor for python, with lots of math support including symbolic functions. Sage code can be intermixed with normal python-code.

The package is quite big, but I have good experiences with it. It is free and open-source.

DSM

As a syntax, sin + cos simply isn't going to work very well. The simplest way to get the general case to work is to give sympy an expression to evaluate. We can let sympify do the hard work of turning a string into a sympy object:

>>> s = raw_input("enter a formula: ")
enter a formula: sin(x) + x**3
>>> s
'sin(x) + x**3'
>>> f = sympy.sympify(s)
>>> f
x**3 + sin(x)

After which we can substitute and evaluate:

>>> f.subs({'x': 2})
sin(2) + 8
>>> f.subs({'x': 2}).evalf()
8.90929742682568

See also my answer here for some other tricks you can pull with a bit of work:

>>> f = definition_to_function("f(x) = sin(x) + x**3")
>>> f(3)
27.14112000805987
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!