[R] Re: log10(), floor() combo issue?
    Uwe Ligges 
    ligges at statistik.uni-dortmund.de
       
    Mon Oct 14 12:18:43 CEST 2002
    
    
  
"E.L. Willighagen" wrote:
> 
> Hi all,
> 
> in my search for a nice binary2decimal method, I received this nice
> code (thanx to Uwe Ligges):
> 
>  bindec <- function(b)
>    sum(as.integer(unlist(strsplit(b, ""))) * 2^(floor(log10(b)):0))
> 
> It fails, however, with:
> 
> > bindec(1000)
> [1] 4
> Warning message:
> longer object length
>         is not a multiple of shorter object length in:
> as.integer(unlist(strsplit(b, ""))) * 2^(floor(log10(b)):0)
> 
> The reason is the combination of floor() and log10():
> 
> log10(1000) = 3
> 
> ok, but:
> 
> floor(log10(1000)) = 2
> 
> ? Ok, I can live with some floating point inaccuracy, but this seems
> at least a bit strange, and to me troublesome as it makes the bindec()
> method fail...
> 
> I've also tried to force the output of log10(1000) into integer format
> with
> 
> floor(as.integer(log10(b)))
> 
> However, with the same disappointing results...
Sorry, I haven't thought about that. Another, numerical more stable
solution is:
  bindec <- function(b){
    temp <- as.integer(unlist(strsplit(b, "")))
    sum(temp * 2^((length(temp) - 1):0))
  }
  bindec(1000)
Uwe Ligges
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
    
    
More information about the R-help
mailing list