1

I have the following double vector that was imported from a data in a spreadsheet. The data represents accounting values.

> amts 
[1]        0.00    2616.79    3908.20       0.00       0.00       0.00      50.25     600.54    2104.29       0.00     800.13     837.08
[13]     588.85     550.57     435.07       0.00    4000.00    5000.00   10000.00  120000.00  266000.00       0.00   16089.71       0.00
[25]   11202.35   21594.32   10238.44       0.00    5500.10       0.01       0.00     296.67     313.79    -430.42     -42.02     -11.99
[37]      -0.20       0.00       0.00       0.00       0.00       0.00   -3519.57   -3323.94   -6815.91   -4540.39  -35268.87  -29260.34
[49]  -26896.01       0.00  -22384.00  -49929.73  -27860.94   -4055.22  -21776.87   -8671.80       0.00    1366.38  -85548.01 -208958.93
[61]   55201.62
> typeof(amts)
[1] "double"

When I go to sum them all together, the value is returning way more decimal places than are necessary. It's like R is adding decimals that aren't there.

> sum(amts)
[1] 1.327294e-11

Oddly, when I sum the vector in chunks, the behavior isn't the same.

> (x <- sum(amts[1:30]))
[1] 482116.7
> (y <- sum(amts[31:61]))
[1] -482116.7
> x + y
[1] 0

I'm curious to understand this behavior and how / why R is manufacturing decimals during the sum() function that don't seem to exist before applying the function.

  • 1
    Does this answer your question? [Controlling number of decimal digits in print output in R](https://stackoverflow.com/questions/2287616/controlling-number-of-decimal-digits-in-print-output-in-r) – Peace Wang Jan 04 '22 at 10:20
  • Could you provide us with your dataset using `dput`? This way we can better answer your question. – Maël Jan 04 '22 at 13:14
  • 1
    Hi @Johnny Williamson. The sum of your vector should be zero. This is a floating point problem. Please find all the necessary explanations in this very inspiring [post](https://blog.revolutionanalytics.com/2009/03/when-is-a-zero-not-a-zero.html). Cheers. – lovalery Jan 04 '22 at 14:24
  • 1
    @lovalery This led me to the solution. Thanks! I prepared an Answer, but it looks like this Question has been closed (even though I don't believe it's equivalent to the Questions/Answers related to controlling decimals in print output). – Johnny Williamson Jan 04 '22 at 20:17

0 Answers0