sympy

Poul Riis priisdk at gmail.com
Thu Mar 31 17:33:16 EDT 2016


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?


Poul Riis


from sympy import *
from time import *
x=Symbol('x')
ftext=diff(sin(x),x)

def fmsympy(t): 
   return ftext.evalf(subs={x:t})

def fm(t):
    return cos(t)

nloop=10000
tstart=time()
for i in range(0,nloop):
    a=fmsympy(1)
dt1=time()-tstart
print(a)
tstart=time()
for i in range(0,nloop):
    a=fm(1.0)
dt2=time()-tstart
print(a)

print(nloop,' evaluations with sympy   : dt1 =',dt1)
print(nloop,' evaluations without sympy: dt2 =',dt2)



More information about the Python-list mailing list