0

Try this code:

R version 3.4.4 (2018-03-15) -- "Someone to Lean On"
Copyright (C) 2018 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)
[...]

> round(55.8/1.8)
[1] 31
> 55.8/1.8
[1] 31
> round(55.8/1.8) == (55.8/1.8)
[1] FALSE
> round(55.8/1.8) - (55.8/1.8)
[1] 3.552714e-15

How is it possible? Is it a bug? I found it after verifying some data in a dataset where I was looking for records where the division between two numbers was not integer, by checking if the round value was equal to the result of / operator.

Nicola Dinapoli
  • 207
  • 2
  • 7

1 Answers1

0

This is because 55.8/1.8 is not exactly 31 in floating point math:

> format(55.8/1.8, digits=22)
[1] "30.99999999999999644729"

This is because the numbers you are using do not have exact floating point representations.

Ryan C. Thompson
  • 40,856
  • 28
  • 97
  • 159
  • What about this example? round(0.11/(0.07+0.22+0.11),2). The expression evaluates to 0.27, even though the inner formula equals 0.275. And if you hand type 0.275 into the round call, you get 0.28 – Yousif Al-Y May 16 '22 at 23:01
  • @YousifAl-Y The inner formula does not equal 0.275. Just like the original example, it equals approximately 0.2749999999999999666933, which rounds down to 0.27. – Ryan C. Thompson May 16 '22 at 23:54