0

I have the following numeric vector taken from a basic data.frame. I want to do a simple sum and it gives me weird results.

x 
[1] -1.06 -5.36  4.74 -5.66  1.64 -2.86  8.04  2.54 -1.36 -0.66

sum(x)
[1] -7.105427e-15

I have tried using cumsum to see if the problem comes from one of the values specifically. I guess the problem is with the last value but I don't understand why.

cumsum(x)
1] -1.060000e+00 -6.420000e+00 -1.680000e+00 -7.340000e+00 -5.700000e+00
 [6] -8.560000e+00 -5.200000e-01  2.020000e+00  6.600000e-01 -7.105427e-15

I have restarted the R session. I'm using version R version 3.6.3 (2020-02-29). And i'm using these libraries to read and reshape the data.

library(readxl)
library(dplyr)
library(tidyr)

Is there a known thing to look for when using specific libraries or a way of showing certain numbers in a particular way? Thanks in advance.

flafont11
  • 137
  • 7

1 Answers1

2

As the link shared by Ben Bolker, if you look at the additions:

> -1.06 + -5.36 + 4.74 + (-5.66) + 1.64 + (-2.86) + 8.04 + 2.54 + (-1.36)
[1] 0.66

Now upon adding the last value of -0.66:

> -1.06 + -5.36 + 4.74 + (-5.66) + 1.64 + (-2.86) + 8.04 + 2.54 + (-1.36) + (-.66)
[1] -0.00000000000000144329

Just to cross check:

> near(-1.06 + -5.36 + 4.74 + (-5.66) + 1.64 + (-2.86) + 8.04 + 2.54 + (-1.36), .66)
[1] TRUE
> 
Karthik S
  • 11,348
  • 2
  • 11
  • 25