[R] strange floor rounding
David Winsemius
dwinsemius at comcast.net
Fri Jul 9 16:35:41 CEST 2010
On Jul 9, 2010, at 10:27 AM, Trafim Vanishek wrote:
> Thanks everybody for referring me to FAQ 7.31 but I don't see how to
> solve
> it.
> I am giving a concrete number and I need to get 58 not 57. Seems,
> there is
> no way?
>
Building on an example on the help page for as.integer, this seems to
be working:
> trnc2 <- function(x) trunc(x) + (trunc(x) < x)*sign(x)*(abs(x -
trunc(x)) < .Machine$double.eps^0.5)
> trnc2(0.01*100)
[1] 1
> trnc2(seq(0, 1, by=0.01)*100)
[1] 0 1 2 3 4 5 6 8 8 9 10 11 12 13 15
15 16 17 18 19
[21] 20 21 22 23 24 25 26 27 29 28 30 31 32 33 34
35 36 37 38 39
[41] 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
56 57 58 57 59
[61] 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
75 76 77 78 79
[81] 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
95 96 97 98 99
[101] 100
> trnc2(-seq(0, 1, by=0.01)*100)
[1] 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11
-12 -13 -14 -15
[17] -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27
-28 -28 -30 -31
[33] -32 -33 -34 -35 -36 -37 -38 -39 -40 -41 -42 -43
-44 -45 -46 -47
[49] -48 -49 -50 -51 -52 -53 -54 -55 -56 -57 -57 -59
-60 -61 -62 -63
[65] -64 -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75
-76 -77 -78 -79
[81] -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91
-92 -93 -94 -95
[97] -96 -97 -98 -99 -100
And after looking at that a bit I came up with a shorter alternate
that seems to work as well:
trnc3 <- function(x) trunc(x+sign(x)* .Machine$double.eps^0.5)
See also ?all.equal
--
David.
> On Fri, Jul 9, 2010 at 4:05 PM, David Winsemius <dwinsemius at comcast.net
> >wrote:
>
>>
>> On Jul 9, 2010, at 9:46 AM, Trafim Vanishek wrote:
>>
>> Dear all,
>>>
>>> might seem and easy question but I cannot figure it out.
>>>
>>> floor(100*(.58))
>>> [1] 57
>>>
>>> where is the trick here?
>>>
>>
>> FAQ 7.31
>>
>>
>> And how can I end up with the right answer?
>>>
>>
>> Define right, please. (There have been several questions in the
>> last week
>> for which FAQ 7.31 was the answer and some of the responses had
>> useful
>> links.)
>>
>> --
>> David Winsemius, MD
>> West Hartford, CT
>>
>>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
David Winsemius, MD
West Hartford, CT
More information about the R-help
mailing list