首页 > 解决方案 > .coeff() 没有给出正确答案 Python Sympy

问题描述

我试图在 sympy 中找到表达式的系数。

我做了一个代码,但它给出了错误的输出。第一个(下面给出)代码是我尝试编写程序的方式(尽管它并不完全正确)。

import sympy as sp

a0, a1, a2, a3, x = sp.symbols("a_0 a_1 a_2 a_3 x")
v = a0 + a1*x + a2*x**2 + a3*x**3
display(v)

print("========================================================================")

v1, θ1, v2, θ2, L = sp.symbols("v1 θ_1 v2 θ_2 L")


v = v.subs([(a0, v1), (a1, θ1*v2), (a2, L*v2 + v1 + θ1/θ2), (a3, θ1*θ2)])
display(v)

print("========================================================================")

display(v.coeff(x, 2))
display(v.coeff(v2))
display(v.coeff(θ2))

这是输出。

在此处输入图像描述

在这里,即使我a0, a1, a2 and a3用其他符号组合替换,我仍然可以调用.coeff()函数并获得一个系数(即使它在第二个中不正确v2

我有另一个代码,我在其中做更多的事情

import sympy as sp

a0, a1, a2, a3, x, L = sp.symbols("a_0 a_1 a_2 a_3 x L")
v1, θ1, v2, θ2 = sp.symbols("v1 θ_1 v2 θ_2")

v = a0 + a1*x + a2*x**2 + a3*x**3 # Equation
θ = sp.diff(v, x)

display(v, θ)

print("=============================================================")

v_1 = v.subs(x, 0) # substituting values for x 
θ_1 = θ.subs(x, 0)
v_2 = v.subs(x, L)
θ_2 = θ.subs(x, L)

display(v_1, θ_1, v_2, θ_2)
# now we got 4 equations in terms of a0, a1, a2 and a3

print("==============================================================")

A = sp.solve((v_1 - v1, θ_1 - θ1, v_2 - v2, θ_2 - θ2), a0, a1, a2, a3) 
# solving system of 4 equations in terms of a0, a1, a2 and a3

display(A)

print("==============================================================")

A0, A1, A2, A3 = A[a0], A[a1], A[a2], A[a3]

display(A0, A1, A2, A3)

print("==============================================================")

v = v.subs([(a0, A0), (a1, A1), (a2, A2), (a3, A3)])
display(v)

print("==============================================================")

display(v.coeff(x, 2)) # this works for x, x**2, x**3 etc

print("==============================================================")

display(v.coeff(v1), v.coeff(θ1), v.coeff(v2), v.coeff(θ2)) # THIS GIVES WRONG ANSWER

这是新代码的输出。这段代码中的所有内容都是正确的,除了最后一行给出了错误的输出。

在此处输入图像描述

在这里,当我打电话.coeff()v1, θ1, v2, θ2,我没有得到正确的答案。

上面给出的是正确答案: 在此处输入图像描述

我试图得到这样的答案。有人可以帮忙吗?我认为问题在于.solve()它的输出。有人能帮我吗?

谢谢你。

标签: pythonsympysolvercoefficientslinear-equation

解决方案


我的错。v = v.expand()以前应该做.coeff()的。


推荐阅读