在网上找到了一些example之后,我可以这样做:
from sympy import var
from sympy import solve
Ldy, Ldz = var('Ldy Ldz')
g, x, y, z = var('g x y z')
xZ, yZ, zZ = var('xZ yZ zZ')
xdd, ydd, zdd = var('xdd ydd zdd')
E1 = z * xdd + (xZ - x) * (g + zdd)
E2 = z * ydd + (yZ - y) * (g + zdd) - Ldy
E3 = -y * xdd + x * ydd - zZ * (g + zdd) + Ldz
out = solve([E1, E2, E3], [xdd, ydd, Ldy])
print(type(xdd))
print("xdd = ", (out[xdd]).factor())
哪个产生xdd = (g + zdd)*(x - xZ)/z
。
现在,按照我自己的公式进行操作:
from sympy import symbols, solve
x, y, z, k12, k26, x0 = symbols("x, y, z, k12, k26, x0")
symbols = x, y, z, k12, k26, x0
eq1 = k12 * x**2 -y
eq2 = k26 * y**3 - z
eq3 = x * 2*y + 6*z - x0
out = solve([eq1, eq2, eq3], [x,y,z])
print("x = ", (out[x]).factor())
取而代之的是TypeError: list indices must be integers or slices, not Symbol
。
我在做什么错了?
答案 0 :(得分:0)
问题在于solve
有多种返回类型:有时它返回一个列表,有时返回一个字典,有时返回一个字典列表。输出形式取决于要求解的方程式的细节:变量数,解数。这意味着应该使用list=True
或dict=True
来强制solve
的输出一致。请注意,dict=True
表示输出是字典的列表,因为可能存在多个解决方案-此处就是这种情况。在您的示例中:
out = solve([eq1, eq2, eq3], [x,y,z], dict=True)
for sol in out:
print("x = ", sol[x].factor())
打印
x = 18**(1/3)*((3*x0 - sqrt(6*k12*k26*x0 + 1)/(k12*k26) + 1/(k12*k26))/k26)**(2/3)*(sqrt(6*k12*k26*x0 + 1) + 1)/(18*k12*x0)
x = -18**(1/3)*((3*x0 + sqrt(6*k12*k26*x0 + 1)/(k12*k26) + 1/(k12*k26))/k26)**(2/3)*(sqrt(6*k12*k26*x0 + 1) - 1)/(18*k12*x0)
x = -2**(1/3)*((3*x0 - sqrt(6*k12*k26*x0 + 1)/(k12*k26) + 1/(k12*k26))/k26)**(2/3)*(3**(2/3) - 3*3**(1/6)*I)*(sqrt(6*k12*k26*x0 +1) + 1)/(36*k12*x0)
x = -2**(1/3)*((3*x0 - sqrt(6*k12*k26*x0 + 1)/(k12*k26) + 1/(k12*k26))/k26)**(2/3)*(3**(2/3) + 3*3**(1/6)*I)*(sqrt(6*k12*k26*x0 +1) + 1)/(36*k12*x0)
x = 2**(1/3)*((3*x0 + sqrt(6*k12*k26*x0 + 1)/(k12*k26) + 1/(k12*k26))/k26)**(2/3)*(3**(2/3) - 3*3**(1/6)*I)*(sqrt(6*k12*k26*x0 + 1) - 1)/(36*k12*x0)
x = 2**(1/3)*((3*x0 + sqrt(6*k12*k26*x0 + 1)/(k12*k26) + 1/(k12*k26))/k26)**(2/3)*(3**(2/3) + 3*3**(1/6)*I)*(sqrt(6*k12*k26*x0 + 1) - 1)/(36*k12*x0)
由于这个和其他原因,SymPy开发人员建议使用solveset and its relatives而不是solve
。具体来说,nonlinsolve
可以在这里使用:
out = nonlinsolve([eq1, eq2, eq3], [x,y,z])
for sol in out:
print("x = ", sol[x].factor())
可打印
x = -18**(1/3)*((3*x0 + sqrt(6*k12*k26*x0 + 1)/(k12*k26) + 1/(k12*k26))/k26)**(2/3)*(sqrt(6*k12*k26*x0 + 1) - 1)/(18*k12*x0)
x = 18**(1/3)*((3*x0 - sqrt(6*k12*k26*x0 + 1)/(k12*k26) + 1/(k12*k26))/k26)**(2/3)*(sqrt(6*k12*k26*x0 + 1) + 1)/(18*k12*x0)
x = 2**(1/3)*((3*x0 + sqrt(6*k12*k26*x0 + 1)/(k12*k26) + 1/(k12*k26))/k26)**(2/3)*(3**(2/3) - 3*3**(1/6)*I)*(sqrt(6*k12*k26*x0 + 1) - 1)/(36*k12*x0)
x = 2**(1/3)*((3*x0 + sqrt(6*k12*k26*x0 + 1)/(k12*k26) + 1/(k12*k26))/k26)**(2/3)*(3**(2/3) + 3*3**(1/6)*I)*(sqrt(6*k12*k26*x0 + 1) - 1)/(36*k12*x0)
x = -2**(1/3)*((3*x0 - sqrt(6*k12*k26*x0 + 1)/(k12*k26) + 1/(k12*k26))/k26)**(2/3)*(3**(2/3) + 3*3**(1/6)*I)*(sqrt(6*k12*k26*x0 +1) + 1)/(36*k12*x0)
x = -2**(1/3)*((3*x0 - sqrt(6*k12*k26*x0 + 1)/(k12*k26) + 1/(k12*k26))/k26)**(2/3)*(3**(2/3) - 3*3**(1/6)*I)*(sqrt(6*k12*k26*x0 +1) + 1)/(36*k12*x0)
solveset及其亲属的返回类型始终是一个SymPy集。