所以我試圖將一個字串函式運算式轉換為一個可以理想地采用 numpy 陣列的函式。
到目前為止,我有這個:
import sympy as sp
expr = "x^2 y^2"
f = sp.sympify(expr)
symbol_list = []
for symbol in f.free_symbols:
symbol = sp.Symbol(str(symbol))
symbol_list.append(symbol)
現在f
可以使用該函式,sp.subs
但我想用一個 numpy 陣列替換x, y
. 有任何想法嗎?
uj5u.com熱心網友回復:
在 SymPy 中,f
稱為符號運算式。Sympy 還公開lambdify
了 ,它允許將符號運算式轉換為數值函式。
# extract the symbols from the symbolic expression: order them alphabetically.
# This will be used to create the signature of the numerical function.
signature = sorted(f.free_symbols, key=str)
print(signature)
# out: [x, y]
# create the numerical function
num_f = lambdify(signature, f)
# evaluation
import numpy as np
x = np.arange(1, 10)
y = 2
print(num_f(x, y))
# out: array([ 5, 8, 13, 20, 29, 40, 53, 68, 85])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/506847.html
上一篇:如何使用函式在三元運算中設定值?