bug in lambdify functionality with trigonometric functions?

201 views
Skip to first unread message

Quirine

unread,
Jan 10, 2015, 12:50:29 PM1/10/15
to sy...@googlegroups.com
Dear Sympy community,
 

The following line of code gives:


>>> from sympy import *

>>> x,y=symbols('x y')

>>> f=lambdify(x,y*cos(x))

>>> f(1)

0.54030230586814*y


works fine, but interchanging x and y:


>>> f=lambdify(x,x*cos(y))

>>> f(1)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

  File "<string>", line 1, in <lambda>

  File "/Users/krol/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/sympy/core/expr.py", line 225, in __float__

    raise TypeError("can't convert expression to float")

TypeError: can't convert expression to float


gives me a headache, 

Does someone know a solution to this?


kind Regards,

Quirine

James Crist

unread,
Jan 10, 2015, 4:44:31 PM1/10/15
to sy...@googlegroups.com
`lambdify` is intended for numeric evaluation (but can be made to evaluate symbolically). By default, the functions `sin`, `cos`, etc... are pulled from `math` or `numpy`, which expect floats (and if not given a float, they attempt to convert to float).

What's happening here, is you're passing in a number for `x`, but `y` is still a symbol, and is enclosed in the function as a local. `lambdify` doesn't know this, and uses `math.cos` by default, which causes the error. Using the `modules` kwarg, you can tell lambdify to use `sympy.cos` instead.

>>> f = lambdify(x, x*cos(y), modules='sympy')
>>> f(1)
cos(y)

You can also pass a dictionary of {function_name_as_string: function} to modules, if you want finer control:

>>> f = lambdify(x, x*cos(y), modules={'cos': sympy.cos})
>>> f(1)
cos(y)

Aaron Meurer

unread,
Jan 13, 2015, 3:05:14 PM1/13/15
to sy...@googlegroups.com
Or it's possible that you meant to do lambdify((x, y), x*cos(y)) to create a two-argument function.

Aaron Meurer

--
You received this message because you are subscribed to the Google Groups "sympy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sympy+un...@googlegroups.com.
To post to this group, send email to sy...@googlegroups.com.
Visit this group at http://groups.google.com/group/sympy.
To view this discussion on the web visit https://groups.google.com/d/msgid/sympy/788a5592-1021-4082-85bb-4d71c907fb8d%40googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages