找出具有约束的方程式的根 [英] Finding the root of an equation with a constraint
问题描述
在python中,我想找到以下形式的方程的根:
In python, I would like to find the roots of equations of the form:
-x * log(x)+(1-x)* log(n)-(1-x)* log(1-x)-k = 0
-x*log(x) + (1-x)*log(n) - (1-x)*log(1 - x) - k = 0
其中n和k是将要指定的参数.
where n and k are parameters that will be specified.
对根的另一个约束是x> =(1-x)/n.因此,就其价值而言,我将过滤掉不满足要求的根.
An additional constraint on the roots is that x >= (1-x)/n. So just for what it's worth, I'll be filtering out roots that don't satisfy that.
我的第一个尝试是使用scipy.optimize.fsolve(请注意,我只是将k和n分别设置为0和1):
My first attempt was to use scipy.optimize.fsolve (note that I'm just setting k and n to be 0 and 1 respectively):
def f(x):
return -x*log(x) + (1-x)*log(1) - (1-x)*log(1-x)
fsolve(f, 1)
使用math.log时,我遇到了价值错误,因为我向日志提供了错误的输入.使用numpy.log给了我一些零除和乘法中的无效值.
Using math.log, I got value-errors because I was supplying bad input to log. Using numpy.log gave me some divide by zeros and invalid values in multiply.
我这样调整了f,只是看它会做什么:
I adjusted f as so, just to see what it would do:
def f(x):
if x <= 0:
return 1000
if x >= 1:
return 2000
return -x*log(x) + (1-x)*log(1) - (1-x)*log(1-x)
现在我得到
/usr/lib/python2.7/dist-packages/scipy/optimize/minpack.py:221: RuntimeWarning: The iteration is not making good progress, as measured by the
improvement from the last ten iterations.
warnings.warn(msg, RuntimeWarning)
使用python,如何求解原始方程式中各种n和k参数的x?
Using python, how can I solve for x for various n and k parameters in the original equation?
推荐答案
fsolve还允许插入从何处开始的猜测.我的建议是绘制方程式,并让用户使用鼠标或通过文本输入初始猜测值作为初始猜测值.您可能还需要更改超出范围的值:
fsolve also allows guesses to be inserted for where to start. My suggestion would be to plot the equation and have the user type a initial guess either with the mouse or via text to use as an initial guess. You may also want to change the out of bounds values:
if x <= 0:
return 1000 + abs(x)
if x >= 1:
return 2000 + abs(x)
通过这种方式,该函数在感兴趣区域之外具有一个斜率,它将引导求解器返回到感兴趣的区域.
This way the function has a slope outside of the region of interest that will guide the solver back into the interesting region.
这篇关于找出具有约束的方程式的根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!