Python Newton-Raphson 求根方法的 OverflowError

Python OverflowError for Newton-Raphson root finding method

x=float(raw_input('Enter a number to show its square root'))
precise = 0.01
g=x/2.0
while abs(g**2-x)>=precise:
   g=g-(g**2-x)/2*g
print g

这是一个基于 Newton-Raphson 求根法的 python 代码。当我在 Canopy 中 运行 这个时,我可以找到 1 的根。但是当我输入 25 来找到根时,它说 OverflowError: (34, 'Result too large') 指向 while abs(g**2-x)>=precise: 行。帮助赞赏

你确定你的算法吗?将 print g 移到 while 循环中,您会看到 g 变得非常非常大,非常快。然后你试图平方它。你的分母应该是 2*g 吗?如果是这样,那么您应该像 (2*g) 一样在它周围加上括号,因为您要除以 2,然后乘以 g。可能不是你想做的。

当使用 Newton-Raphson 法求根时,我总是发现将我的标准代码用于此算法并在必要时指定它很有用。也许你也会发现这很有用。

ftn1 <- function(x){
  fx <- log(x) -exp(-x)
  dfx <- 1/x + exp(-x)
  return(c(fx,dfx))
}


newtonraphson <- function(ftn, x0, tol = 1e-9, max.iter = 100) {

  x <- x0
  fx <- ftn(x)
  iter <- 0
  while ((abs(fx[1]) > tol) && (iter < max.iter)) {
    x <- x - fx[1]/fx[2]
    fx <- ftn(x)
    iter <- iter + 1
    cat("At iteration", iter, "value of x is:", x, "\n")
  }
  if (abs(fx[1]) > tol) {
    cat("Algorithm failed to converge\n")
    return(NULL)
  } else {
    cat("Algorithm converged\n")
    return(x)
  }
}
newtonraphson(ftn1, 0.1)