Description Usage Arguments Examples
Implementation of the NestWhile
function from the Wolfram langauge.
Syntax order has been changed so that the function is compatible with the pipe operator (see %>%
).
1 | nest_while(x, expr, cond, m = 1, maxit = 1e+05, n = 0, xname = "x")
|
x |
an object or a variable name. |
expr |
an expression or a function to be evaluated recursively. |
cond |
a condition to be evaluated. |
m |
return results of the last |
maxit |
maximum number of iterations. |
n |
additional iterations to be completed after the condition has been satisfied. |
xname |
character string containing the name of the argument that will be used recursively. |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | ## Some of these examples are directly taken from the Wolfram documentation
## number of terms required in taylor expansion to achieve a target error.
nest_while(0, x+1, exp(1) - sum(1/factorial(0:x)) > 1e-5)
## collatz sequence
nest_while(1214, ifelse(x %% 2 == 0, x/2, 3*x+1), x != 1, m = "all")
## root finding algorithms
f <- function(x) x^5 - 4 * x^3 + 159
secant <- function(x) c(x[2], x[2] - f(x[2]) * diff(x)/diff(f(x)))
nest_while(c(2, 3), secant, abs(f(x[2])) > 10^-5)
## Happy number
## http://stackoverflow.com/questions/18675285/digit-sum-function-in-r
digitsum2 <- function(x) sum((floor(x / 10^(0:(nchar(x) - 1))) %% 10)^2)
res <- sapply(1:1000, function(x) nest_while(x, digitsum2, x!= 1 & x!= 4))
which(res == 1)
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.