获取一个恰好名为dot的未定义函数,并将其作为lambdify的一部分:
import numpy
import sympy
class dot(sympy.Function):
pass
x = sympy.Symbol('x')
a = sympy.Matrix([1, 0, 0])
f = sympy.lambdify(x, dot(a.T, x))
x = numpy.array([3, 2, 1])
print(f(x))
惊喜:这真的有效!
显然,字符串 "dot" 以某种方式被提取并替换为点积的实现。有谁知道吗?
上面的结果是[3]。但是,我希望获得标量 3。 (如何)我可以修改 f() 来实现它?
请您参考如下方法:
我不是 sympy 用户,但是我引用了 lambdify 的文档它说:
If not specified differently by the user, SymPy functions are replaced as far as possible by either
python-math,numpy(if available) ormpmathfunctions - exactly in this order. To change this behavior, the “modules” argument can be used. It accepts:
- the strings “math”, “mpmath”, “numpy”, “numexpr”, “sympy”
- any modules (e.g. math)
- dictionaries that map names of sympy functions to arbitrary functions
- lists that contain a mix of the arguments above, with higher priority given to entries appearing first.
所以看起来如果你安装了 python-math 它将使用它,如果没有但你安装了 numpy 它将使用 numpy 的版本,否则 mpmat 然后描述如何修改此行为。
在您的情况下,只需提供一个 modules 值,该值是一个字典,将名称 dot 映射到一个函数,该函数可以根据需要返回一个标量。
我的意思的一个例子:
>>> import numpy as np
>>> import sympy
>>> class dot(sympy.Function): pass
...
>>> x = sympy.Symbol('x')
>>> a = sympy.Matrix([1,0,0])
>>> f = sympy.lambdify(x, dot(a.T, x), modules=[{'dot': lambda x, y: np.dot(x, y)[0]}, 'numpy'])
>>> y = np.array([3,2,1])
>>> print(f(y))
3
>>> print(type(f(y)))
<class 'numpy.int64'>
正如您所看到的,通过操纵 modules 参数,您可以实现您想要的。我在这里的实现绝对是幼稚的,但您可以将其概括为:
>>> def my_dot(x, y):
... res = np.dot(x, y)
... if res.ndim == 1 and res.size == 1:
... return res[0]
... return res
此函数检查普通 dot 的结果是否为标量,如果是则返回普通标量,否则返回与 np.dot 相同的结果。
