-1

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!

star_star
  • 11
  • 1

2 Answers2

2
logstar<-function(x){if (x<1) 0 else 1 + logstar(log(x))}
mrip
  • 14,913
  • 4
  • 40
  • 58
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