1

我试图Andsympy使用时重新映射lambdify,但它似乎不起作用......

import sympy
x, y = sympy.symbols('x y')
f = sympy.And(x, y)


def my_and(x, y):
    print("inside my_and")
    return x and y

f_fn = sympy.lambdify([x, y], f, {"And": my_and})
print(f_fn(True, False))

结果不会显示“inside my_and”,这意味着它my_and不起作用。其他功能sin如下所示。我不知道哪里出错了...

import sympy
x = sympy.symbols('x')
f = sympy.sin(x)


def my_sin(x):
    print("inside my_sin")
    return 0.


f_fn = sympy.lambdify([x], f, {"sin": my_sin})
print(f_fn(0.))

这个将准确inside my_sin输出0.

我想重新映射And到我的功能,那我该怎么办?

4

1 回答 1

0

help(f_fn)例如sin显示:

Help on function _lambdifygenerated:

_lambdifygenerated(x)
    Created with lambdify. Signature:
    
    func(x)
    
    Expression:
    
    sin(x)
    
    Source code:
    
    def _lambdifygenerated(x):
        return sin(x)
    

在四处摸索之后,我发现映射定义了__globals__这个函数:

In [224]: f_fn.__globals__.keys()
Out[224]: dict_keys(['sin', 'x', 'builtins', 'range', '__builtins__'])

In [225]: f_fn.__globals__['sin']
Out[225]: <function __main__.my_sin(x)>

您的“和”示例的帮助:

Help on function _lambdifygenerated:

_lambdifygenerated(x, y)
    Created with lambdify. Signature:
    
    func(x, y)
    
    Expression:
    
    x & y
    
    Source code:
    
    def _lambdifygenerated(x, y):
        return x and y

虽然有类似的映射:

In [229]: f_and.__globals__.keys()
Out[229]: dict_keys(['and', 'y', 'x', 'builtins', 'range', '__builtins__'])

In [230]: f_and.__globals__['and']
Out[230]: <function __main__.my_and(x, y)>

但我认为这不起作用,因为andinx and y是 Python 关键字,是操作员角色,而不是函数。它不能映射到其他东西。

and这是 Python的正常短路:

In [231]: f_and(False,'foo')
Out[231]: False

In [232]: f_and(True,'foo')
Out[232]: 'foo'

In [240]: f_and(x>0,y)
...
TypeError: cannot determine truth value of Relational

刚刚意识到我用过and,而你用过And

In [241]: f_and = lambdify([x,y],f,{"And": my_and})

    def _lambdifygenerated(x, y):
        return x and y

In [242]: f_and.__globals__.keys()
Out[242]: dict_keys(['And', 'y', 'x', 'builtins', 'range', '__builtins__'])

In [243]: f_and.__globals__['And']
Out[243]: <function __main__.my_and(x, y)>

映射和函数之间的联系就更少了。

像这样的映射{"And": my_and}不会直接影响代码翻译。那就是他们不生产

def foo(x,y):
   return my_and(x,y)   # if my_sin(x)

相反,它们决定了 Python 代码的运行方式。


如果我省略映射

f_and1 = lambdify([x,y], f)

代码是

def _lambdifygenerated(x,y):
        return logical_and.reduce((x,y))

f_and1.__globals__提供了一大堆numpy功能,包括

In [254]: f_and1.__globals__['logical_and']
Out[254]: <ufunc 'logical_and'>

并且行为是numpy明智的:

In [261]: f_and1([True,True],[True,False])
Out[261]: array([ True, False])

lambdify([x,y],f,[{"And": my_and},'numpy'])还给我logical_and翻译。

于 2021-12-14T03:41:31.117 回答