从值数组评估 sympy 表达式 [英] Evaluate sympy expression from an array of values
问题描述
我正在尝试使用 sympy,但遇到了一个我无法解决的问题.
I'm experimenting with sympy and I've hit upon an issue I can't work out.
使用 scipy 我可以编写一个表达式并为 x 值数组计算它,如下所示:
Using scipy I can write an expression and evaluate it for an array of x values as follows:
import scipy
xvals = scipy.arange(-100,100,0.1)
f = lambda x: x**2
f(xvals)
使用 sympy 我可以写出如下相同的表达式:
Using sympy I can write the same expression as follows:
import sympy
x = sympy.symbols('x')
g = x**2
我可以通过执行以下操作来评估这个表达式的单个值:
I can evaluate this expression for a single value by doing the following:
g.evalf(subs={x:10})
但是,我无法像使用 scipy 那样计算如何针对 x 值数组评估它.我该怎么做?
However I can't work out how to evaluate it for an array of x values, like I did with scipy. How would I do this?
推荐答案
首先,目前 SymPy 不保证支持 numpy 数组,而这正是您在这种情况下想要的.查看此错误报告 http://code.google.com/p/sympy/issues/detail?id=537
First of all, at the moment SymPy does not guarantee support for numpy arrays which is what you want in this case. Check this bug report http://code.google.com/p/sympy/issues/detail?id=537
第二,如果你想用数字来评估许多值,SymPy 不是最好的选择(毕竟它是一个符号库).使用 numpy 和 scipy.
Second, If you want to evaluate something numerically for many values SymPy is not the best choice (it is a symbolic library after all). Use numpy and scipy.
然而,以数字方式评估某事物的一个有效理由是,推导要评估的表达式很困难,因此您在 SymPy 中推导它,然后在 NumPy/SciPy/C/Fortran 中对其进行评估.要将表达式转换为 numpy 只需使用
However, a valid reason to evaluate something numerically will be that deriving the expression to be evaluated was hard so you derive it in SymPy and then evaluate it in NumPy/SciPy/C/Fortran. To translate an expression to numpy just use
from sympy.utilities.lambdify import lambdify
func = lambdify(x, big_expression_containing_x,'numpy') # returns a numpy-ready function
numpy_array_of_results = func(numpy_array_of_arguments)
查看lambdify 的文档字符串以获取更多详细信息.请注意,lambdify 仍然存在一些问题,可能需要重写.
Check the docstring of lambdify for more details. Be aware that lambdify still has some issues and may need a rewrite.
顺便提一下,如果您想多次真正计算表达式,您可以使用 sympy 中的 codegen/autowrap 模块来创建包装和可从 python 调用.
And just as a side note, if you want to evaluate the expressions really many times, you can use the codegen/autowrap module from sympy in order to create fortran or C code that is wrapped and callable from python.
可以在 wiki https://github.com/sympy/sympy/wiki/Philosophy-of-Numerics-and-Code-Generation-in-SymPy
这篇关于从值数组评估 sympy 表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!