Newton's Method for calculating the square root
MySqrt <- function(x, eps = 1e-06, itmax = 100, verbose = FALSE) {
newtroot <- c()
for (j in 1:length(x)) {
j <- j
Sqrt <- x[j]/2
for (i in 1:itmax) {
if (x[j] < 0 && verbose == TRUE) {
print("Warning: input must be greater than 0!")
}
if (x[j] < 0) {
Sqrt <- NaN
newtroot[j] <- NaN
break
}
if (verbose == TRUE) {
Iteration <- i
print(sprintf("Iteration %d: %f", Iteration, Sqrt))
}
if (x[j] == 0) {
Sqrt <- 0
newtroot[j] <- Sqrt
}
if (abs(Sqrt * Sqrt - x[j]) < eps) {
newtroot[j] <- Sqrt
break
} else {
Sqrt <- (Sqrt + x[j]/Sqrt)/2
newtroot[j] <- Sqrt
}
}
if (verbose == TRUE && length(x) > 1) {
print(Sqrt)
}
}
return(newtroot)
}
12 * MySqrt(0:2)
## [1] 0.00 12.00 16.97
MySqrt(1/7)
## [1] 0.378
MySqrt(-2:4, verbose = T)
## [1] "Warning: input must be greater than 0!"
## [1] NaN
## [1] "Warning: input must be greater than 0!"
## [1] NaN
## [1] "Iteration 1: 0.000000"
## [1] 0
## [1] "Iteration 1: 0.500000"
## [1] "Iteration 2: 1.250000"
## [1] "Iteration 3: 1.025000"
## [1] "Iteration 4: 1.000305"
## [1] "Iteration 5: 1.000000"
## [1] 1
## [1] "Iteration 1: 1.000000"
## [1] "Iteration 2: 1.500000"
## [1] "Iteration 3: 1.416667"
## [1] "Iteration 4: 1.414216"
## [1] "Iteration 5: 1.414214"
## [1] 1.414
## [1] "Iteration 1: 1.500000"
## [1] "Iteration 2: 1.750000"
## [1] "Iteration 3: 1.732143"
## [1] "Iteration 4: 1.732051"
## [1] 1.732
## [1] "Iteration 1: 2.000000"
## [1] 2
## [1] NaN NaN 0.000 1.000 1.414 1.732 2.000
MySqrt(-2:4)
## [1] NaN NaN 0.000 1.000 1.414 1.732 2.000
sqrt(-2:4)
## Warning: NaNs produced
## [1] NaN NaN 0.000 1.000 1.414 1.732 2.000
MySqrt(2:4)
## [1] 1.414 1.732 2.000
sqrt(2:4)
## [1] 1.414 1.732 2.000