python - .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()
它的输出。有人能帮我吗?
谢谢你。
解决方案
我的错。v = v.expand()
以前应该做.coeff()
的。
推荐阅读
- c# - 确定输入 ID 是否保留在目录项集合中
- angular - 带有 Angular 10 的 CodeIgniter 4 API:$this->request->getPost() 始终为空
- ansible - PyNetBox API 是否可以选择验证自签名证书的 CA 证书?
- javascript - _isEqual 的 Lodash 返回键
- c++ - 如何在 cpp 中创建应该在 windows 和 linux 上工作的套接字?
- html - 如何在 AMP Html 电子邮件模板中设置 FORM 输入和操作
- liferay - 自定义 Portlet 中的空 Portlet 主体
- cuda - CUDA 不能使用所有可用的常量内存
- unity3d - 如何使 2D 对撞机在关卡开始之前不对已经碰撞的对象执行任何功能
- google-apps-script - Google Apps 脚本失败摘要:alta