Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More than one module for lambdify in sympy

I am trying to make lambdify understand to expect more than one type of input using the modules keyword argument. According to the source code of lambdify (http://docs.sympy.org/dev/_modules/sympy/utilities/lambdify.html), this can be done by using lists of the arguments, but i am not able to do so.

import sympy
from sympy import lambdify
x,y=sympy.symbols('x y')
from sympy.parsing.sympy_parser import parse_expr
func=lambdify(x,parse_expr(exp(x)),modules=["numpy","sympy"])

func(array([3,4]))

gives

array([ 20.08553692,  54.59815003])

but when i try

func(y)

i get an

Attribute error:exp

What am i doing wrong here? Shouldn't func accept both numpy and sympy types? Any help appreciated!!

like image 741
krishna Avatar asked Aug 25 '14 22:08

krishna


People also ask

What is SymPy Lambdify?

lambdify() method. With the help of sympy. lambdify() method, we can convert a SymPy expression to an expression that can be numerically evaluated. lambdify acts like a lambda function, except it, converts the SymPy names to the names of the given numerical library, usually NumPy or math.

Does SymPy work with NumPy?

In general, SymPy functions do not work with objects from other libraries, such as NumPy arrays, and functions from numeric libraries like NumPy or mpmath do not work on SymPy expressions.

How do you evaluate a SymPy expression?

To evaluate a numerical expression into a floating point number, use evalf . SymPy can evaluate floating point expressions to arbitrary precision. By default, 15 digits of precision are used, but you can pass any number as the argument to evalf .

What does from SymPy import * mean?

It simply says that you want all of the module's variables imported into your module's namespace.


1 Answers

The modules don't dispatch or anything like that. The way that lambdify works is that it creates

lambda x: exp(x)

where exp comes from the namespace of the module(s) you chose. lambdify(x, exp(x), ['numpy', 'sympy']) is roughly equivalent to

from sympy import *
from numpy import *
# Various name replacements for differences in numpy naming conventions, like
# asin = arcsin
return lambda x: exp(x)

If you want to provide a custom function that dispatches, you can use something like Saullo Castro's example. You can also use this with lambdify by providing a dict, like

import numpy as np
import sympy

def myexp(x):
    if isinstance(x, np.ndarray):
        return np.exp(x)
    else:
        return sympy.exp(x)

func = lambdify(x, exp(x), [{'exp': myexp}, 'numpy'])

This gives

>>> func(np.array([1, 2]))
array([ 2.71828183,  7.3890561 ])
>>> func(sympy.Symbol('y'))
exp(y)
like image 82
asmeurer Avatar answered Sep 28 '22 12:09

asmeurer