Python sympy symbols

前端 未结 1 511
忘掉有多难
忘掉有多难 2021-01-20 10:11

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          


        
1条回答
  •  生来不讨喜
    2021-01-20 11:09

    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

    0 讨论(0)
提交回复
热议问题