您可以使用 .subs() 方法将浮点数值替换为相应的符号:
import sympy as sp
import numpy as np
x1 = sp.Symbol('x1')
x2 = sp.Symbol('x2')
x3 = sp.Symbol('x3')
X = sp.Matrix([x1, x2, x3])
myM = 4 * sp.ones(3, 3)
smyM=sp.diag(*X) + myM - sp.diag(*np.diag(myM))
fcoefs = [(a, f) for a, f in (zip([x1, x2, x3], np.array([0.1,0.2,0.3])))]
fmyM = smyM.subs(fcoefs)
smyM
Out[105]:
Matrix([
[x1, 4, 4],
[ 4, x2, 4],
[ 4, 4, x3]])
fmyM
Out[106]:
Matrix([
[0.1, 4, 4],
[ 4, 0.2, 4],
[ 4, 4, 0.3]])
在进行以下操作之后,sympy.matrices.dense.MutableDenseMatrix
矩阵看起来很好:
fmyM @ myM
Out[107]:
Matrix([
[32.4, 32.4, 32.4],
[32.8, 32.8, 32.8],
[33.2, 33.2, 33.2]])
可能需要将其转换为np.array以便与numpy完全使用
以下是我的一些代码,展示了我使用的模式:
def ysolv(coeffs):
x,y,a,b,c,d,e = symbols('x y a b c d e')
ellipse = a*y**2 + b*x*y + c*x + d*y + e - x**2
y_sols = solve(ellipse, y)
print(*y_sols, sep='\n')
num_coefs = [(a, f) for a, f in (zip([a,b,c,d,e], coeffs))]
y_solsf0 = y_sols[0].subs(num_coefs)
y_solsf1 = y_sols[1].subs(num_coefs)
f0 = lambdify([x], y_solsf0)
f1 = lambdify([x], y_solsf1)
return f0, f1
f0, f1 = ysolv(t[0])
y0 = [f0(x) for x in xs]
y1 = [f1(x) for x in xs]
...
来源:https://stackoverflow.com/a/41232062/6876009(是的,我的“feeloutXrange”是一个如此糟糕的hack,以至于必须展示出来)