0

I encountered an error that makes no sense to me. When using min(diff(x)) on integer numbers, no error occurs. But when using doubles, there is something wrong.

x <- c(1, 3, 5, 6, 8, 10)
min(diff(x))
# 1
min(diff(x)) == 1
# TRUE

But when doing this on doubles, the following happens...

x <- c(0.1, 0.3, 0.5, 0.6, 0.8, 1.0)
min(diff(x))
# 0.1
min(diff(x)) == 0.1
# FALSE

Also, the result of min(diff(x)) has the identical format as a regular double variable.

Can you reproduce this? I am using R 3.0.1

Is this error worth reporting?

Stingery
  • 432
  • 4
  • 16
  • If this is not reproducible, and because floating points (see first comment) are problematic sometimes, I guess this error is not worth reporting. Thanks! – Stingery Jul 17 '13 at 10:58
  • 1
    It is reproducible. It's a known limitation of floating-point arithmetic. – Joshua Ulrich Jul 17 '13 at 11:00
  • 2
    Such comparisons should be done with `all.equal`, e.g. `all.equal(min(diff(x)), 0.1)`. – QuantIbex Jul 17 '13 at 11:03
  • 2
    @QuantIbex `all.equal` has its little quirks. When just comparing two scalars, as is being done here, it's safer to test `abs(x-y)<.Machine$double.eps^.5` – Carl Witthoft Jul 17 '13 at 12:13
  • @Carl Witthoft would this be different from `all.equal(x, y, tol=.Machine$double.eps^.5)`? – QuantIbex Jul 17 '13 at 12:42
  • @QuantIbex Try `all.equal(3,4)` and see what you get. – Hong Ooi Jul 17 '13 at 12:48
  • @Hong Ooi How does your example help me to determine if `abs(x-y)<.Machine$double.eps^.5` is different from `all.equal(x, y, tol=.Machine$double.eps^.5)`? – QuantIbex Jul 17 '13 at 12:58
  • @QuantIbex Just try it and see what you get. – Hong Ooi Jul 17 '13 at 13:02
  • 2
    @QuantIbex read the help page for `all.equal` -- if your two objects have different attributes, you will get an annoying :-) message even if the actual numeric values are the same. – Carl Witthoft Jul 17 '13 at 13:03
  • The other thing about `all.equal` is that if the values are NOT all equal, you get back a string like "hey numbskull, these numbers aren't equal!" instead of a neat, tidy `FALSE`. – Hong Ooi Jul 17 '13 at 13:15
  • @Hong Ooi The reason I dared ask you is that I did try, but didn't see your point. Or at least, I thought that your point was not the fact that the output of `all.equal` was a character when the numbers differ. I thought there was some other mystery (at least to me) due to floating points representations. Anyway, thanks for pointing this out. – QuantIbex Jul 17 '13 at 13:23

0 Answers0