我有一个方程要解。该方程可以描述为上面的公式。N 和 S 是常数,例如 N = 201 和 S = 0.5。我在python中使用sympy来解决它。python脚本如下:
from sympy import *
x=Symbol('x')
print solve( (((1-x)/200) **(1-x))* x**x - 2**(-0.5), x)
但是,有一个RuntimeError: maximum recursion depth exceeded in __instancecheck__
我也尝试过使用 Mathematica,它可以输出 0.963 的结果
http://www.wolframalpha.com/input/?i=(((1-x)%2F200)+ (1-x))*+x x+-+2**(-0.5)+%3D+0
欢迎任何建议。谢谢。
Assuming that you don't want a symbolic solution, just a value you can work with (like WA's 0.964), you can use mpmath
for this. I'm not sure if it's actually possible to express the solution in radicals - WA certainly didn't even try. You should already have it installed as SymPy
Requires: mpmath
Specifically, mpmath.findroot
seems to do what you want. It takes an actual callable Python object which is the function to find a root of, and a starting value for x. It also accepts some more parameters such as the minimum error tol
and the solver to use which you could play around with, although they don't really seem necessary. You could quite simply use it like this:
import mpmath
f = lambda x: (((1-x)/200) **(1-x))* x**x - 2**(-0.5)
print mpmath.findroot(f, 1)
我只是使用 1 作为起始值 - 你可能会想到一个更好的。从图形的形状来看,只有一个根可以找到,并且可以很容易地接近它,不需要花哨的求解器,所以这应该就足够了。此外,考虑到“mpmath 是一个用于任意精度浮点运算的 Python 库”,如果您愿意,您应该能够从中获得非常高精度的答案。它的输出为
(0.963904761592753 + 0.0j)
这实际上是一个 mpmath 复合体或mpc
对象,
mpc(real='0.96390476159275343', imag='0.0')
如果您知道它的虚值为 0,则可以使用以下任一方法:
In [6]: abs(mpmath.mpc(23, 0))
Out[6]: mpf('23.0')
In [7]: mpmath.mpc(23, 0).real
Out[7]: mpf('23.0')
以mpf
.格式“提取”单个浮点数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句