0

I am using R version 3.6.0 (2019-04-26). I noticed something strange with the precision of rational numbers when using dput. For example:

1/3
# [1] 0.3333333
dput(1/3)
# 0.333333333333333

Why does dput produce an object with many more decimal places that is not identical to the original?

Alex
  • 15,186
  • 15
  • 73
  • 127
  • It only _displays_ more precision. Try `options(digits = 16)` the type in `1/3` – G5W Aug 20 '20 at 00:24
  • hmm. if it only displays more precision why is: `identical(1/3, 0.333333333333333)` false on my system? – Alex Aug 20 '20 at 00:30
  • 2
    That's because `dput()` also doesn't display all the digits by default. `identical(1/3, 0.33333333333333331483)` will return TRUE. Floating point numbers are tricky. Learn more at [why are these numbers not equal](https://stackoverflow.com/questions/9508518/why-are-these-numbers-not-equal) – MrFlick Aug 20 '20 at 00:35
  • Thanks... this should probably be a separate question, but how do you get `dput` to display the output with sufficient precision so that `identical` returns true? – Alex Aug 20 '20 at 00:38
  • Ok, i've worked out that if I print with digits = 22 I get `identical(1/3, 0.33333333333333331)` to be `TRUE`. Which is not the decimal you have (although that one also returns true on my system). – Alex Aug 20 '20 at 00:40
  • `identical` doesn't seem like the right tool for comparing floating point numbers. I think `all.equal` is what you want - `all.equal(1/3, 0.333333333333333)` == `TRUE` for example. – thelatemail Aug 20 '20 at 00:41
  • @Alex Well, note that `identical(0.33333333333333331483, 0.33333333333333331)` is TRUE. R can only keep track of so many decimals. I think my number may have lied. I had used `sprintf("%.20f",1/3)` to generate it. What are you actually doing that you need this equality? Doing quality testing with floating point numbers isn't very straightforward. – MrFlick Aug 20 '20 at 00:44
  • My usual strategy for unit testing is to `dput` the object I know to be correct and use it for testing. Today I am generating unit tests involving matrices. But obviously the precision affects the output of `identical` and I couldn't work out why `dput` was not working the way I have been using it. So, thank you. – Alex Aug 20 '20 at 01:06

0 Answers0