In R, I would like to create a function that returns the smallest n such that the n-th repetition of the natural logarithm gives a value smaller than one. Ex.: fun(9182) = 3 because ln(ln(ln(9182))) = 0,793 < 1. Any suggestions will be appreciated!
Asked
Active
Viewed 302 times
-1
-
Welcome to SO - could you let us know what you have tried already? – chopper Oct 04 '13 at 20:06
2 Answers
2
@mrip's answer works well for single values. If you'd like a function that works for vectors, you'll want to use ifelse()
rather than if
:
> logstar <- function(x){ifelse(x<1,0,1 + logstar(ifelse(x<1,x,log(x))))}
> x = c(0.5,1,100,10000,1E8)
> logstar(x)
[1] 0 1 3 3 4
The ifelse()
in the recursive call to logstar()
prevents log()
from generating NaN
in some cases.

Simon
- 10,679
- 1
- 30
- 44