gpt4 book ai didi

r - R中的牛顿法

转载 作者:行者123 更新时间:2023-12-04 14:59:29 26 4
gpt4 key购买 nike

我在尝试实现牛顿法的代码以找到平方根的值时遇到问题(使用迭代)。我试图让函数在达到一定的精度后停止打印值,但我似乎无法让它工作。下面是我的代码。

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 语句不起作用?

最佳答案

这应该有效:

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

关于r - R中的牛顿法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19394061/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com