将每个元素映射到表达式 [英] map each element to expression

查看:18
本文介绍了将每个元素映射到表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

import sympy
import numpy as np
from sympy.utilities.lambdify import lambdify
from collections import OrderedDict

arr = [np.array([ 1, 2]), np.array([ 5, 6])]
a,b = sympy.symbols('a b')
var = [a,b]
expr = ['a+cos(b)', 'a+cos(b)*2']

f = lambdify( var, expr, 'numpy')

vals = OrderedDict(zip(var, arr)).values()
f(*vals)

我收到:

[array([ 1.28366219,  2.96017029]), array([ 1.56732437,  3.92034057])]

我想收到:

[array([ 1.28366219,  3.92034057])]

因此:

1+np.cos(5) = 1.28366219

2 +np.cos(6)*2 = 3.92034057

推荐答案

鉴于您实现 f 的方式,我认为获得所需输出的唯一方法是直接访问所需元素.当您为 ab 传递值时,f 中的两个表达式都将被评估并在列表中返回(如您定义的那样).你可以查看f.func_doc

Given the way you implemented f, I think the only way to get your desired output is to access the desired elements directly. When you pass values for a and b, both expressions in f will be evaluated and returned in a list (as you defined it). You can check f.func_doc

f.func_doc
"Created with lambdify. Signature:\n\nfunc(a, b)\n\nExpression:\n\n['a+cos(b)', 'a+cos(b)*2']"

然后

f(1, np.pi)

返回

[0.0, -1.0]

正如预期的那样,其中 0.0 对应于 a+cos(b)-1.0 对应于 a+cos(b)*2.

as expected, where 0.0 corresponds to a+cos(b) and -1.0 to a+cos(b)*2.

在您的示例中,您可以简单地执行以下操作:

In your example you could simply do:

[vali[i] for i, vali in enumerate(f(*vals))]

它为您提供所需的输出:

which gives you the desired output:

[1.2836621854632262, 3.9203405733007317]

我想单独定义表达式会比您目前在列表中定义更容易,但我不知道您选择结构的原因:

I guess it would be easier to define the expressions separately rather than in a list as you currently do it but I don't know the reason for the structure you chose:

from sympy import cos

f1 = lambdify((a, b), a+cos(b))
f2 = lambdify((a, b), a+cos(b)*2)

res = [np.array([f1(1, 5), f2(2, 6)])]

给出

[array([ 1.28366219,  3.92034057])]

这篇关于将每个元素映射到表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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