python - Python 中的牛顿拉夫森算法不起作用;只估计一个方向

标签 python r approximation

首先阅读:问题很简单,绝对值的括号应该围绕实际分数。现在的问题是它实际上不够精确,它忽略了 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,但不能高于 0.5。在这些地方使用 print 甚至表明它没有运行代码中的 #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])

最佳答案

问题是

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

应该是

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

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

关于python - Python 中的牛顿拉夫森算法不起作用;只估计一个方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15484443/

相关文章:

Python Flask Flasgger (Swagger) webargs - HTTP PUT 主体中的字符串列表

r - 如何合并 R 中的两个日期向量?

r - 使用 auto.arima() 和 xreg 进行样本外预测

c++ - 提高超越方程解的精度

python - 返回字符串创建元组 Python 递归

python - 值错误 : Attempted relative import in non-package not for tests package

python - 将旋转的 xticklabel 与其各自的 xticks 对齐

r - 带有聚合值的 fiddle 图 (geom_violin)

algorithm - 最多 3 种颜色算法