[R] why the base::round(0.015, 2) returns 0.02?
Duncan Murdoch
murdoch@dunc@n @ending from gm@il@com
Wed Nov 28 19:14:27 CET 2018
On 28/11/2018 8:49 AM, Philipp Upravitelev wrote:
> Dear colleagues,
> could you help me with the function base::round()? I can't understand how
> it works.
>
> For example, when I want to round 0.015 to the second digit, base::round()
> returns 0.02.
>
> But the real representation of the 0.015 is different:
>> sprintf('%.20f', 0.015)
> [1] "0.01499999999999999944"
>> 0.015 == 0.01499999999999999944
> [1] TRUE
>> round(0.015, 2)
> [1] 0.02
This calculation is informative:
100*0.015 - 1.5
which gives 0 on my system. So even though 0.015 isn't exactly
representable, when you multiply by 100, you get the exactly correct
result. Then the apparent rule for round(x, 2) is: multiply by 100,
round to an integer, divide by 100.
Duncan Murdoch
>
> Therefore, according to the arithmetic rules, rounded 0.014 to the second
> digit is 0.01. Also, the round() function in other programming languages
> (Python, Java) returns 0.01. It is a bit counterintuitive but
> mathematically correct.
>
> I'll be very pleased if you could help me to figure out why the
> base::round(0.015, 2) returns 0.02 and what is the purpose of this feature.
>
> Best regards,
> Philipp Upravitelev
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.
>
More information about the R-help
mailing list