我想找到满足特定方程的所有实数。我很容易在 Mathematica 中找到这些值
Solve[n*9^5 == 10^n-1, n]
其中gives both 0 and 5.51257 ;但是当我使用 SymPy 的 (0.7.3; Python 2.7.5)
solve
n = sympy.symbols('n')
sympy.solve(n*9**5 - 10**n-1, n)
我似乎只得到看起来像 0 的东西,而不是第二个值,这正是我真正想要的。
我怎样才能让 SymPy 产生我正在寻找的重要解决方案?我应该使用不同的功能或包吗?
最佳答案
solve
只给出符号解,所以如果它找不到解的封闭形式,它不会返回它。如果你只关心数值解,你想要在 SymPy 中是 nsolve
,或者您可以使用更面向数值的 Python 库。例如
sympy.nsolve(n*9**5 - 10**n-1, n, 5)
会给你你正在寻找的解决方案。
使用
solve
的问题是有无限多个解,每个解对应于 LambertW 函数的一个分支。见 WolframAlpha对于完整的解决方案集。不幸的是,only the principal branch of LambertW is implemented in SymPy .在此问题得到解决之前,另一种解决问题的方法是手动评估
solve
返回的 LambertW。在另一个分支上,使用 mpmath.lambertw
.最简单的方法是使用 lambdify
:s = sympy.solve(n*9**5 - 10**n-1, n)
import sympy.mpmath
# Replace -1 with any integer. -1 gives the other real solution, the one you want
lambdify([], s, [{'LambertW': lambda x: sympy.mpmath.lambertw(x, -1)}, "mpmath"])()
这给
[mpf('5.5125649309411875')]
.字典告诉
lambdify
评估 LambertW
函数使用 -1
分支,使用 mpmath。 "mpmath"
告诉它对可能在解决方案中的任何其他函数使用 mpmath。
关于python-2.7 - 为什么 SymPy 的求解器只返回一个简单的解决方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19768711/