问题
When I use "x" and "z" as symbols, I have no problem with this code:
from sympy import *
x, z = symbols('x z')
y = -6*x**2 + 2*x*z**0.5 + 50*x - z
solve((diff(y, x), diff(y, z)))
y.subs({x: 5, z: 25})
But when I use "q" and "a", solve does not give me any solution.
q, a = symbols('q a')
y = -6*q**2 + 2*q*a**0.5 + 50*q - a
solve((diff(y, q), diff(y, a)))
y.subs({q: 5, a: 25})
As you can see I use "subs" to check that there is no typo in the objective function.
UPDATE: I used "Symbol" to set each variable individually, but again using "q" and "a" does not work.
# This works
x = Symbol('x')
z = Symbol('z')
y = -6*x**2 + 2*x*z**0.5 + 50*x - z
solve((diff(y, x), diff(y, z)))
# This does not work
q = Symbol('q')
a = Symbol('a')
y = -6*q**2 + 2*q*a**0.5 + 50*q-a
solve((diff(y, q), diff(y, a)))
Thank you.
回答1:
Got it!
It all depends on an alphabetic order of your variables.
If you substitute x
for z
and z
for x
in your first example it will also stop working.
Internally solve sends the expression to the function _solve
in sympy.solvers
which then tries to solve your equation and fails many times.
Finally as a last effort what it does is it tries to solve -sqrt(a) + q
or x - sqrt(z)
by picking symbols from it through an internal function _ok_syms
, with an argument that sorts those alphabetically (even without this argument it still would, but if wrapped with reversed
it magically makes your examples works in the exactly opposite way).
And so it does solve x - sqrt(z)
as x: sqrt(z)
and -sqrt(a) + q
as a: q**2
.
While in the first case it ends up with an easily solvable 50 - 10*sqrt(z)
, in the second case it is lost on -12*q + 2*sqrt(q**2) + 50
as it is not able to simplify sqrt(q**2)
.
source: a lot of testing on: https://github.com/sympy/sympy/blob/master/sympy/solvers/solvers.py
来源:https://stackoverflow.com/questions/64637215/python-sympy-symbols