结合numpy和sympy [英] Combining numpy with sympy

查看:431
本文介绍了结合numpy和sympy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

p = classp();
for i in range(1,10):
   x = numpy.array([[2],[4],[5]])
   print p.update(x)

class classp:
   def __init__(self):
       self.mymodel = array([2*x[1]], [3*x[0]], [x[2]]);
   def update(self, x):
       return self.mymodel #replace x(0)...x(1) with the given parameter

我的问题与上面的代码有关,我想尽可能使用sympy定义模型,然后在update函数中用x值替换sympy变量.是否有可能?我该怎么办?

My question is related the code above, I would like to define a model using sympy if it's possible, afterwards in the update function replace the sympy variables with the x values. Is it possible? How can I do that?

推荐答案

我可以为您提出两个解决方案.

I can propose you two solutions.

首先,有一个DeferedVector是为与lambdify一起使用而创建的:

Firstly, there is DeferedVector that was created for use with lambdify:

In [1]: from sympy.matrices import DeferredVector

In [2]: v = DeferredVector('v')

In [3]: func = lambdify(v, Matrix([v[1], 2*v[2]]))

In [4]: func(np.array([10,20,30]))
Out[4]: 
       [[20] 
        [60]]

但是lambdify不能满足我的口味.

However lambdify does too much magic for my taste.

另一种选择是使用.subs方法:

Another option is to use the .subs method:

In [11]: x1, x2, x3 = symbols('x1:4')

In [12]: m = Matrix([x2,2*x1,x3/2])

In [13]: m.subs({x1:10, x2:20, x3:30})
Out[13]: 
        ⎡20⎤
        ⎢  ⎥
        ⎢20⎥
        ⎢  ⎥
        ⎣15⎦

您可以像这样创建用于替换的字典:

You can create the dictionary for the substitution like that:

dict(zip(symbols('x1:4'), your_value_array)).

不要忘记所有返回对象都是sympy矩阵.要将它们转换为numpy数组,只需使用np.array(the_matrix_in_question)且不要忘记指定dtype,否则它将默认为dtype=object.

Do not forget that all the return objects are sympy matrices. To convert them to numpy arrays just use np.array(the_matrix_in_question) and do not forget to specify the dtype, otherwise it will default to dtype=object.

这篇关于结合numpy和sympy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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