pythonsympysolvercoefficientslinear-equation

.coeff() does not give correct answer Python Sympy


I am trying to find the coefficients of an expression in sympy.

I made a code but it gives a wrong output. the first(given below) code is how I am trying to write the program(eventhough it is not completely correct).

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))

This is the output.

enter image description here

Here, even though I substituted a0, a1, a2 and a3 with other combinations of symbols, I can still call .coeff() function and get a coefficient(eventhough it is not correct in second one with v2)

I have another code in which I do some more things

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

This is the output of the new code. Everything in this code is correct except the last line which gives a wrong output.

enter image description here

Here, when I call .coeff() for v1, θ1, v2, θ2, I don't get the correct answer.

Given above is the correct answer: enter image description here

I am trying to get an answer like this. Can someone help? I think the problem is in the .solve() and it's output. Can someone help me?

Thank you.


Solution

  • My bad. Should have done v = v.expand() before .coeff().