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
274 views
in Technique[技术] by (71.8m points)

python - Evaluate sympy expression from an array of values

I'm experimenting with sympy and I've hit upon an issue I can't work out.

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)

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})

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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

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.

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)

Check the docstring of lambdify for more details. Be aware that lambdify still has some issues and may need a rewrite.

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.

EDIT: An updates list of ways to do numerics in SymPy can be found on the wiki https://github.com/sympy/sympy/wiki/Philosophy-of-Numerics-and-Code-Generation-in-SymPy


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

...