sympy
Oscar Benjamin
oscar.j.benjamin at gmail.com
Thu Mar 31 18:26:29 EDT 2016
On 31 March 2016 at 22:33, Poul Riis <priisdk at gmail.com> wrote:
> Den onsdag den 30. marts 2016 kl. 13.17.33 UTC+2 skrev Poul Riis:
>> Is it possible to transfer results from sympy to 'normal' python.
>>
>> In the case below I think my intention is clear enough but it does not work as intended. How can it be done?
>>
>> Poul Riis
>>
>> from sympy import *
>> x=Symbol('x')
>> ftext=diff(1/(x**2+1),x)
>>
>> def f(t):
>> return ftext.subs(x,'t')
>>
>> print(f(3))
>
> Well, cos(1) should have been cos(1.0) (which forces numerical evaluation, try example below).
> I am just trying to implement one little thing that all CAS tools can do in a few lines, namely finding the derivative of a given function followed by evalution of numerical values, something like:
> define(fm(x),diff(f(x),x))
> fm(1.0)
>
> Sympy can find the derivative, and once that has been completed I would expect that there is some way to find numerical values just as fast as if the derivative had been given 'by hand'. But how exactly?
I assume that you're responding to me (even though your post is a
reply to yourself).
Robert Kern already answered this question earlier in the thread:
$ isympy
IPython console for SymPy 0.7.5 (Python 2.7.9-64-bit) (ground types: gmpy)
These commands were executed:
>>> from __future__ import division
>>> from sympy import *
>>> x, y, z, t = symbols('x y z t')
>>> k, m, n = symbols('k m n', integer=True)
>>> f, g, h = symbols('f g h', cls=Function)
Documentation can be found at http://www.sympy.org
In [1]: f = lambdify(x, sin(x).diff(x))
In [2]: f
Out[2]: <function numpy.<lambda>>
In [3]: f(1)
Out[3]: 0.540302305868
We can pull apart this function f returned here:
In [4]: import dis
In [5]: dis.dis(f)
1 0 LOAD_GLOBAL 0 (cos)
3 LOAD_FAST 0 (x)
6 CALL_FUNCTION 1
9 RETURN_VALUE
In [6]: f.func_globals['cos']
Out[6]: <function math.cos>
So the function f returned by lambdify uses math.cos which is the
64-bit float function I mentioned earlier (i.e. the faster one). You
can pass an int in and it will be coerced to float. You should find
that the performance of f is as good as lambda x: math.cos(x).
So lambdify takes an expression and a sequence of symbols and
generates a function whose arguments are substituted for the sequence
of symbols. The return value of the function is the result of
substituting the arguments for the symbols in the expression. I think
this is what you asked for.
--
Oscar
More information about the Python-list
mailing list