Sympy:lambdify 使得对数组的操作总是导致数组,对于常量也是如此? [英] Sympy: lambdify such that operations on arrays always result in arrays, also for constants?

查看:18
本文介绍了Sympy:lambdify 使得对数组的操作总是导致数组,对于常量也是如此?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在很多点上评估用户给出的函数 (f') 的导数.这些点在一个列表中(或 numpy.array、pandas.Series...).当 f' 依赖于一个 sympy 变量时,我获得了预期值,但当 f' 是一个常数时则不是:

I need to evaluate the derivative of functions (f') given by the user in many points. The points are in a list (or numpy.array, pandas.Series...). I obtain the expected value when f' depends on a sympy variable, but not when f' is a constant:

import sympy as sp

f1 = sp.sympify('1')
f2 = sp.sympify('t')

lamb1 = sp.lambdify('t',f1)
lamb2 = sp.lambdify('t',f2)

print(lamb1([1,2,3]))
print(lamb2([1,2,3]))

我得到:

1
[1, 2, 3]

第二个没问题,但我希望第一个是一个列表.

The second is alright, but I expected that the first would be a list of ones.

这些函数在一个矩阵中,并且是 sympy 操作的最终结果,例如取导数.f1 和 f2 的确切形式因问题而异.

These functions are in a matrix and the end result of sympy operations, such as taking derivatives. The exact form of f1 and f2 varies per problem.

推荐答案

lamb1 是一个返回常量 1 的函数:def Lamb1(x): return 1.

lamb1 is a function that returns the constant 1: def lamb1(x): return 1.

lamb2 是一个返回其参数的函数:def Lamb2(x): return x.

lamb2 is a function that returns its argument: def lamb2(x): return x.

因此,输出非常符合预期.

So, the output is very well the expected one.

这是一种可能有效的方法.我将 f2 的测试函数更改为 t*t 因为这在我的测试中更烦人(处理 Pow(t,2)).

Here is an approach that might work. I changed the test function for f2 to t*t as that was more annoying in my tests (dealing with Pow(t,2)).

import sympy as sp
import numpy as np

f1 = sp.sympify('1')
f2 = sp.sympify('t*t')

def np_lambdify(varname, func):
    lamb = sp.lambdify(varname, func, modules=['numpy'])
    if func.is_constant():
        return lambda t: np.full_like(t, lamb(t))
    else:
        return lambda t: lamb(np.array(t))

lamb1 = np_lambdify('t', f1)
lamb2 = np_lambdify('t', f2)

print(lamb1(1))
print(lamb1([1, 2, 3]))
print(lamb2(2))
print(lamb2([1, 2, 3]))

输出:

1
[1 1 1]
4
[1 4 9]

这篇关于Sympy:lambdify 使得对数组的操作总是导致数组,对于常量也是如此?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆