本文介绍了在sympy lambdify多个模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让lambdify了解期望多个类型,使用模块关键字参数的输入。据lambdify源$ C ​​$ C(),这可以通过使用的参数列表来完成的,但我不能这样做。

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

array([ 20.08553692,  54.59815003])

但是当我尝试

func(y)

我得到一个

Attribute error:exp

我究竟做错了什么?不应该FUNC同时接受numpy的和sympy类型?
任何帮助AP preciated !!

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

推荐答案

模块不调度之类的东西。该lambdify的工作方式是,它创建

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

lambda x: exp(x)

其中, EXP 来自您所选择的模块(S)的命名空间。 lambdify(X,EXP(X),['numpy的','sympy'])大致相当于

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)

如果您想提供一个调度自定义功能,可以使用类似Saullo卡斯特罗的例子。您也可以通过lambdify提供的字典,就像使用

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'])

这给了

>>> func(np.array([1, 2]))
array([ 2.71828183,  7.3890561 ])
>>> func(sympy.Symbol('y'))
exp(y)

这篇关于在sympy lambdify多个模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 02:01