Why does the lexicographical ordering of symbol names in sympy make a difference?

Viewed 59

Consider this code:

from sympy import *
q, a = symbols('q a')
y = -6*q**2 + 2*q*a**0.5 + 50*q - a
print(y)
r = solve((diff(y, q), diff(y, a)))
print(r)

Result:

2*a**0.5*q - a - 6*q**2 + 50*q
[]

So it fails to find any solutions. But this code find a solution:

from sympy import *
a, q = symbols('a q')
print(y)
y = -6*a**2 + 2*a*q**0.5 + 50*a - q
r = solve((diff(y, a), diff(y, q)))
print(r)

Result:

-6*a**2 + 2*a*q**0.5 + 50*a - q
[{a: 5.00000000000000, q: 25.0000000000000}]

The only difference between the two is that the roles of a and q have been swapped. Why the difference in behavior for what would reasonably be considered two functionally identical code blocks?

I played a bunch with this. It turns out that for any substitution of symbol names in this code, whenever the name of the first symbol mentioned in symbols('<name1> <name2>') is lexicographically smaller than the second symbol's name, a solution is found. Whenever the opposite is true, a solution is not found. I've tried many combinations. For example, symbols('qqq qqr') leads to a solution, but symbols('qqq qqp') does not. This holds true for any two symbol names. In one order, you get a solution. In the other, you don't.

I've searched the sympy documentation, and can find no mention of the constraint that symbols provided to the symbols() function should be in ascending sorted order. Why this behavior? What is going on here?

UPDATE: Per @superbrain's fine suggestion, I've had the code print y in each case. It's interesting that the two results are different, probably because of lexicographical differences in how the names of the terms relate. Aha! There might be something here then. But aren't the two functions equivalent, and wouldn't they have to be unless sympy is screwing up?

0 Answers
Related