R中的牛顿方法

时间:2013-10-16 02:02:41

标签: r newtons-method

在尝试实现Newton方法的代码以找到平方根的值时(使用迭代),我遇到了一个问题。我试图让功能在达到一定精度后停止打印值,但我似乎无法使其正常工作。以下是我的代码。

MySqrt <- function (x, eps = 1e-6, itmax = 100, verbose = TRUE){
  i <- 1
  myvector <- integer(0)
  GUESS <- readline(prompt="Enter your guess: ")
  GUESS <- as.integer(GUESS)
  while(i <= itmax){
      GUESS <- (GUESS + (x/GUESS)) * 0.5
      myvector <- c(myvector, GUESS)
      if (abs(GUESS-x) < eps) break
      i <- i + 1
  }

  myvector

为什么if语句不起作用?

2 个答案:

答案 0 :(得分:3)

UPDATE:

请参阅@ RichieCotton对@ agstudy答案的评论。我同意Richie,事实上使用@ agstudy的方法更有意义。


原始答案:

你的功能很好,你的数学已经关闭了 GUESSx不应该(必要)关闭,但GUESS * GUESSx应该是。MySqrt <- function (x, eps = 1e-6, itmax = 100, verbose = TRUE){ i <- 1 myvector <- integer(0) GUESS <- readline(prompt="Enter your guess: ") GUESS <- as.integer(GUESS) while(i <= itmax){ GUESS <- (GUESS + (x/GUESS)) * 0.5 myvector <- c(myvector, GUESS) browser(expr={i == 10 || abs(GUESS-x) < eps}) if (abs((GUESS*GUESS)-x) < eps) break ### <~~~~ SEE HERE i <- i + 1 } myvector } 和{{1}}。

{{1}}

答案 1 :(得分:3)

这应该有效:

MySqrt <- function (x, eps = 1e-6, itmax = 100, verbose = TRUE){
  i <- 1
  myvector <- vector(mode='numeric',itmax)  ## better to allocate memory
  GUESS <- readline(prompt="Enter your guess: ")
  GUESS <- as.numeric(GUESS)
  myvector[i] <- GUESS
  while(i <= itmax){
    GUESS <- (GUESS + (x/GUESS)) * 0.5
    if (abs(GUESS-myvector[i]) < eps) break
    i <- i + 1
    myvector[i] <-  GUESS
  }
  myvector[seq(i)]
}

MySqrt(2)
Enter your guess: 1.4
[1] 1.400000 1.414286 1.414214