Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sympy: order of result from solving a quadratic equation

Tags:

python

sympy

I solved a quadratic equation using sympy:

import sympy as sp
q,qm,k,c0,c,vt,vm = sp.symbols('q qm k c0 c vt vm')
c = ( c0 * vt - q * vm) / vt
eq1 = sp.Eq(qm * k * c / (1 + k * c) ,q)
q_solve = sp.solve(eq1,q)

Based on some testing I figured out that only q_solve[0] makes physical sense. Will sympy always put (b - sqrt(b**2 - 4*a*c))/2a in the first place ? I guess, it might change with an upgrade ?

like image 713
Moritz Avatar asked Jul 04 '15 13:07

Moritz


People also ask

Can SymPy solve equation?

The solvers module in SymPy implements methods for solving equations. solve() is an older more mature general function for solving many types of equations.

Can SymPy show steps?

By capturing the inputs and outputs of all of these small methods we can collect a great quantity of information about the steps that SymPy takes. We can see that exp. _eval_derivative took in exp(x) and returned exp(x) and that sin. _eval_derivative took in sin(exp(x)) and returned cos(exp(x))*exp(x).


1 Answers

A simple test to answer your question is to symbolically solve the quadratic equation using sympy per below:

import sympy as sp
a, b, c, x = sp.symbols('a b c x')
solve( a*x**2 + b*x + c, x)

this gives you the result:

[(-b + sqrt(-4*a*c + b**2))/(2*a), -(b + sqrt(-4*a*c + b**2))/(2*a)]

which leads me to believe that in general the order is first the + sqrt() solution and then the - sqrt() solution.

For your program q_solve[0] gives you:

(c0*k*vt + k*qm*vm + vt - sqrt(c0**2*k**2*vt**2 - 2*c0*k**2*qm*vm*vt + 2*c0*k*vt**2 + k**2*qm**2*vm**2 + 2*k*qm*vm*vt + vt**2))/(2*k*vm)

this is still the x= (-b + sqrt(b**2-4*a*c))/(2*a) answer, the negative sign from the b term goes away as a result of the distribution of the signs of the variables within the solution

like image 148
bern Avatar answered Sep 23 '22 09:09

bern