2

In R, consider:

floor(c(50, 55, 56, 57, 58))
#> [1] 50 55 56 57 58

, but:

floor(c(0.5*100, 0.55*100, 0.56*100, 0.57*100, 0.58*100))
#> [1] 50 55 56 56 57

Is not affected by brackets:

floor(c(0.5, 0.55, 0.56, 0.57, 0.58)*100)
#> [1] 50 55 56 56 57
floor(c((0.5*100), (0.55*100), (0.56*100), (0.57*100), (0.58*100)))
#> [1] 50 55 56 56 57

Works also for objects:

x <- 0.57*100

floor(x)
#> [1] 56

Also happens for some other numbers between 1 and 100:

x <- diff(floor(seq(0, 1, 0.01)*100))
names(x) <- seq(0, 0.99, 0.01)*100
x
#>  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 
#>  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1 
#> 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 
#>  1  1  0  2  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1 
#> 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 
#>  1  1  1  1  1  0  2  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1 
#> 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 
#>  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1

Why is this?

EDIT, additional question: is there a way to calculate floor for x <- 0.57*100 correctly (i.e. evaluate it before passing into the floor() function)?

Created on 2022-03-30 by the reprex package (v2.0.1)

Mikko
  • 7,530
  • 8
  • 55
  • 92
  • 3
    See here . And chapter 1 of The R Inferno. – TarJae Mar 30 '22 at 14:03
  • 1
    The first two vectors are, in fact, unequal. It's because of the precision of floating-point numbers. See also https://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-doesn_0027t-R-think-these-numbers-are-equal_003f. – tmfmnk Mar 30 '22 at 14:08
  • 2
    To illustrate the answer in TarJae's link, you can type `sprintf("%.30f",.57)` and see that the actual number in R is a tiny bit smaller than `.57` and therefore `floor(.57 *100)` is `56`. – Gilean0709 Mar 30 '22 at 14:08
  • Thanks people, I get it now :) Perhaps someone (@Gilean0709 ?) could answer this? I think the answer to my additional question could be `0.57*100 + 1e-6` or is that the safest way? – Mikko Mar 31 '22 at 08:48

0 Answers0