求解包含绝对值的方程,其中 python 3

Solving an equation containing absolute value, with python 3

我正在尝试用 python 3.6.3 求解以下方程:

我做到了

from sympy import *
x = Symbol('x', real=True)
solve(abs((abs(x**2-1)-x))-x)

但我收到以下消息:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python36-32\lib\site-packages\sympy\solvers\solvers.py", line 1065, i
n solve
solution = _solve(f[0], *symbols, **flags)
  File "C:\Python36-32\lib\site-packages\sympy\solvers\solvers.py", line 1366, i
n _solve
candidates = _solve(piecewise_fold(expr), symbol, **flags)
  File "C:\Python36-32\lib\site-packages\sympy\solvers\solvers.py", line 1634, i
n _solve
raise NotImplementedError('\n'.join([msg, not_impl_msg % f]))
NotImplementedError: multiple generators [x, Abs(-x**2 + x + 1)]
No algorithms are implemented to solve equation -x + Abs(-x**2 + x + 1)

但是使用 python 2.7.14 和 matlab 我得到了答案。 我错过了什么吗?

如果您使用当前母版并手动将表达式重写为 Piecewise,这将得到 [1, -1 + sqrt(2), 1 + sqrt(2)]。显然,由 solve 自己完成的重写是不完整的:

>>> solve((abs((abs(x**2-1)-x))-x).rewrite(Piecewise))
[1, -1 + sqrt(2), 1 + sqrt(2)]

可以使用以下差异更改 SymPy 代码库以更正问题:

diff --git a/sympy/solvers/solvers.py b/sympy/solvers/solvers.py
index 172d504..96bfa94 100644
--- a/sympy/solvers/solvers.py
+++ b/sympy/solvers/solvers.py
@@ -1020,8 +1020,13 @@ def _sympified_list(w):
         # Abs
         fi = fi.replace(Abs, lambda arg:
             separatevars(Abs(arg)) if arg.has(*symbols) else Abs(arg))
-        fi = fi.replace(Abs, lambda arg:
-            Abs(arg).rewrite(Piecewise) if arg.has(*symbols) else Abs(arg))
+        while True:
+            was = fi
+            fi = fi.replace(Abs, lambda arg:
+                (Abs(arg).rewrite(Piecewise) if arg.has(*symbols)
+                else Abs(arg)))
+            if was == fi:
+                break

         for e in fi.find(Abs):
             if e.has(*symbols):