1

首先阅读:问题只是绝对值的括号应该围绕实际分数。现在的问题是它实际上不够精确,它忽略了 0.000001,并且更喜欢 0.0001 作为容差(当我要求它接近 55 时,它停在 54.994397921372205)。我将容差增加到疯狂的 0,然后是 1,但例如接近 50,它估计为 49.14!糟糕的!为什么会这样?

更新:它必须是float()

我试图找到属于基于某些向量的函数的 theta。我让这段代码在 R 中运行,我试图将它从 R 字面上翻译成 Python。

当 grensscore 等于 50 时,我想近似 Theta 的值。我有一个 theta = 0.5 的起始值,然后它在 R 中迭代。在 R 中只需要大约 11 次迭代就可以达到这一点。

可悲的是,这在 Python 中不起作用,我将它隔离了这么多:由于某种原因,这些值只能低于 0.5,但不能高于。在这些地方使用打印甚至表明它没有#a在代码中运行该部分,而该#b部分正在运行。这表明该值永远不会上升,因此我永远找不到像 0.4 这样的值(因为它必须上升 0.5、0.25、0.37.5、0.4375 等,但它只能下降;0.5、0.25、0.125然后迟早停止)

我可以看到它运行#b。很多时候它必须下降,但它永远不会上升。我也切换了它们,看看是否有顺序效应,但没有:它根本不会评估它是真的(即使我知道它是真的)任何人都可以看到出了什么问题,因为这是在 R 中工作?

def CalcTheta(grensscore, alpha, beta):
    theta = 0.5
    estimate = [10000]   # I just set this to not error on the check
    up = 1
    down = 0

    while((math.fabs(sum(estimate)) - grensscore) > 0.00001):

        if estimate == [10000]:     # I set it like this, 
            estimate = [grensscore] # so it will skip the first run

        # a.
        if (sum(estimate) - grensscore) < 0:
            down = theta
            print(down)
            theta = (theta + up) / 2
            print(theta)

        #b.
        if (sum(estimate) - grensscore) > 0:
            print(up, down, theta)
            up = theta
            theta = (theta + down) / 2
            print(up, down, theta)

        for x in range(len(beta)):
            if x == 0:
                estimate = []

            estimate.append(math.exp(alpha[x] * (theta - beta[x]))  / (1 + math.exp(alpha[x] * (theta - beta[x]))))

    return(theta)

CalcTheta(50, data[:,1], data[:,2])
4

2 回答 2

1

问题是

while(math.fabs(sum(estimate)) - grensscore) > 0.00001):

应该

while(math.fabs(sum(estimate) - grensscore)) > 0.00001):

对于另一部分,它不是 a float,因此它并没有变得非常精确。

于 2013-03-18T19:44:06.860 回答
0

有一些图书馆可以为您做到这一点。我建议使用 Scipy ( scipy.optimize.newton)。可以在这里找到食谱:

http://code.activestate.com/recipes/576762-newton-raphson-root-finding/

于 2013-03-18T19:00:36.813 回答