0

I have just started with R and am stuck on this bug.

fuel_efficiency<-c(28.2, 28.3, 28.4, 28.5, 29.0)
mean=28.48
deviation<-(fuel_efficiency-mean)
deviation
sum(deviation)

I have written this code to subtract the mean from the elements of the fuel efficiency vector to get the deviation vector. Then am trying to get the sum of the updated deviation vector.

The sum answer should return 0 but instead gives something like -3.552714e-15

The deviation vector is printed properly as expected.

#[1] -0.28 -0.18 -0.08  0.02  0.52
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66

2 Answers2

1

This are just rounding errors, -3.552714e-15 is a very, very small number: Computers are notoriously bad at handling decimal numbers, (one could even say they are just not able to do it exactly). To overcome this R provides a function to check for equality:

all.equal(sum(deviation), 0)

This returns:

[1] TRUE
dario
  • 6,415
  • 2
  • 12
  • 26
0
format(sum(deviation), scientific = FALSE)

Your answer is very close to zero. It's a rounding error. R uses IEEE 754 double-precision floating point numbers. Read more here: https://en.wikipedia.org/wiki/Double-precision_floating-point_format

penguin
  • 1,267
  • 14
  • 27