4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Sympyのsubsメソッドで配列の計算をしたかった

Posted at

subsメソッドでは駄目みたいで、sympy.lambdifyという関数を使う必要があるっぽい。

subs_vs_lambdify.py
# coding:utf-8


import numpy as np
import sympy as sp


# sympy の変数を作る
x = sp.Symbol('x')
y = sp.Symbol('y')

# numpy の配列を作る
arrX = np.arange(12, dtype='float64').reshape((3, 4))
arrY = np.ones((3, 4))

# sympy の関数を作る
symbolFunc = 2*x + y

# subs メソッドで配列を代入
resSubs = symbolFunc.subs([(x, arrX), (y, arrY)])
print(resSubs)
# ==> 2*x + y
# 配列は計算できないっぽい

# lambdify を使って計算してみる
# まずは関数を作る
lambdifyFunc = sp.lambdify([x, y], symbolFunc)
# 作った関数の引数に配列を渡す
resLambdify = lambdifyFunc(arrX, arrY)
print(resLambdify)
# ==> [[ 1.  3.  5.  7.]
#      [ 9. 11. 13. 15.]
#      [17. 19. 21. 23.]]
# こっちは計算してくれた
4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?