Newton-raphson 脚本冻结以尝试获取大量数据

Newton-raphson script freezes in attempt to root great numbers

我正在尝试使用此公式给出的随机数的 newton-raphson 算法求平方根: 一 = 米 * 10 ^ c 其中 m 是范围 (0,1) 中的随机浮点数,c 是范围 (-300,300) 中的随机整数。 我编写的代码完美地工作,根精度为 0.01,c 在范围 (-30,30) 中,但是当我使用任务中给出的 c 范围时冻结或 returns 错误结果。

这里是牛顿函数的代码 def newton_raphson(a): iterations_count = 0

x_n_result = a/2

while abs(x_n_result - a / x_n_result) > 0.01:

    x_n_result = (x_n_result + a/x_n_result)/2
    iterations_count = iterations_count + 1

    if x_n_result*x_n_result == a:

        break

iterations.append(iterations_count)
results.append(x_n_result)
print("Result of function", x_n_result)

return

以及根号随机化的部分

for i in range(0, 100):
    m = random.uniform(0, 1)
    c = random.randint(-30, 30)
    a = m * 10 **c
    random_c.append(c)
    numbers.append(a)

    print("Number to root : ", i, "|",  a, '\n')
    newton_raphson(a)

根据 c 的值绘制的迭代量图

plt.bar(random_c, iterations, color='red')

脚本应该对 100 个随机数求根,然后根据 c 的值绘制求根数所需的迭代量。问题就像我之前说的那样,c 值的范围合适。我相信它必须对变量范围做一些事情。任何建议如何解决这个问题?

首先观察到你的逻辑会得到平方根,而不是立方根。

第二点是您的随机数可以包含负值,这些负值永远不会收敛于平方根。

如果你真的想要一个立方根,你可以这样做:

def cubic(number):
    result = number
    while abs(number/result/result - result) > 0.01:
        result += (number/result/result - result)/2
    return result

您也可以通过创建一个 newton/raphson 通用函数来以通用方式处理此问题,该函数将 delta 函数作为参数以用于数字参数:

def newtonRaphson(delta,n):
    result = n
    while abs(delta(n,result)) > 0.01:
        result += delta(n,result)/2
    return result

def cubic(n,r): return n/r/r - r
def sqrt(n,r):  return n/r - r

将 newtonRaphson 方法与您选择的 delta 函数结合使用:

newtonRaphson(sqrt,25)   # 5.000023178253949

newtonRaphson(cubic,125) # 5.003284700817307