0

R is getting a very simple subtraction wrong:

> 4.04 - 4.02
[1] 0.02
> 4.04 - 4.02 == 0.02
[1] FALSE
> 4.04 - 4.02 > 0.02
[1] TRUE

4.04 minus 4.02 gets me something close to, but greater than, 0.02. Similar operations sometimes yield the correct result:

> 0.04 - 0.02 == 0.02
[1] TRUE
> 4.51 - 4.01 == 0.5
[1] TRUE

And sometimes not:

> 0.98 - 0.96 == 0.02
[1] FALSE
> 0.98 - 0.96 > 0.02
[1] TRUE
> 4.1 - 4 == 0.1
[1] FALSE
> 4.1 - 4 < 0.1 # this one is getting something lower, not greater, than 0.1
[1] TRUE

Any clue on what might be going on here? I'm using R version 4.2.0 on macOS 12.4 (freshly updated from 4.1.1 and 11.6.5 in the hope of solving the problem, but it persisted).

EDIT

Just tried the same operations in Excel and the problem is also there, meaning it's not restricted to R.

4.04 - 4.02 yields 0.0200000000000005.

4.1 - 4 results in 0.0999999999999996.

Guess I should get in touch with Apple Support...

jocateme
  • 1
  • 1
  • 2
    Computers aren't actually very good at floating point math (numbers with decimals) since they use base-2 numbers but humans use base-10 numbers. There's a lot of small rounding that happens. It's never a good idea to try to test for exact equality with decimal numbers. Usually you check if they are "close enough". This is not unique to R. You'll find the same thing in javascript and C and many other languages. This has nothing to do with your particular operating system. – MrFlick Jun 15 '22 at 18:12
  • @MrFlick thanks for this clarifying answer! I'm just starting to read about it in the question that mine was flagged as duplicate of and honestly I'm surprised I have only now stumbled upon this issue considering how pervasive it is! – jocateme Jun 15 '22 at 18:19
  • R (and some others) is generally good about getting it right for large-enough numbers, but there are (as you see) corner cases. Often it just works, but when it doesn't, there is no flag to say it doesn't work, it just silently resolves to 'not equal'. For research, if you're curious, two other references: https://stackoverflow.com/q/588004 and https://en.wikipedia.org/wiki/IEEE_754 – r2evans Jun 15 '22 at 18:26
  • Many more examples at https://0.30000000000000004.com – Kieran Jun 15 '22 at 18:28

0 Answers0