Reputation: 3
I am trying to solve an equation using an ansatz with a number of independent terms that all have different coefficients. Sympy is trying to find an answer in terms of the independent terms instead of just the coefficients, I feel like I am missing something but have tried everything I could think of/google.
To show a minimal problem I have the following example:
from sympy import *
x,y,z= symbols('x y z')
a1, a2, a3 = symbols('a1 a2 a3')
expr = a1*x + a2*y + a3*z + y
solve(expr,[a1,a2,a3])
the result is:
a1 = -a3 z/x; a2 = -1
What I would want to have is:
a1 = 0; a2 = -1; a3 = 0.
I feel like I am missing something, or is this plainly not possible with sympy.solve or another simple function. I could think of writing my own solver to solve the problem but if there is an 'easy' solution, that would be preferable.
Upvotes: 0
Views: 76
Reputation: 19125
The coefficients of x,y,z
must be zero in order for the sum to be zero (as you have stated) so that can be stated as:
from sympy import *
v=x,y,z= symbols('x y z')
a1, a2, a3 = symbols('a1 a2 a3')
expr = a1*x + a2*y + a3*z + y
expanded = expr.expand()
coeffs = [expanded.coeff(vi) for vi in v] # you now have 3 equations
>>> solve(coeffs,[a1,a2,a3])
{a1: 0, a2: -1, a3: 0}
Upvotes: 1