0

I was trying to my statistics homework using R when I ran into a problem with the sum() function. Given this vector:

-18.4,  -5.4,   1.6,   5.6,  16.6

When I tried to use sum on the vector I got the following result:

2.220446e-15

If I do it a different way (the way I got that data) then I get another answer:

class2

[1]  65  78  85  89 100

class2mean

[1] 83.4

l<-class2-class2mean

sum(l)

[1] -2.842171e-14

l

[1] -18.4  -5.4   1.6   5.6  16.6

Obviously that answer is not correct. However when I tried to do the same calculation by 'hand' I got another result:

-18.4+-5.4+1.6+5.6+16.6

[1] 7.105427e-15

Finally I had to give up and just use my calculator. If anybody can provide me with some help or answers. Obviously I must be doing something wrong, but I do not know what and as this is such a fundamental function, I need to know how to use it correctly and effectively. Thank you!

aosmith
  • 34,856
  • 9
  • 84
  • 118
Nick31415
  • 9
  • 1
  • 6
    The sum is equal to zero within the accuracy of floating point arithmetics. – RHertel Sep 11 '15 at 17:59
  • 3
    ...and your calculator is just as subject to the limitations and oddities of floating point arithmetic as R is. – joran Sep 11 '15 at 18:02
  • 5
    The answers to this question (http://stackoverflow.com/q/9508518/4303162) explain floating point arithmetic in some detail. – Stibu Sep 11 '15 at 18:07
  • @Stibu, Thanks that provides some information on the subject. Though the focus of that post is on floating point arithmetic comparison and evaluation. How can I avoid this 'problem' or overcomer it in everyday use. Especially in use of fundamental functions. – Nick31415 Sep 11 '15 at 18:44
  • You could for instance round your result to obtain exactly zero instead of small numbers: `round(-18.4+-5.4+1.6+5.6+16.6, 12)`. – Stibu Sep 11 '15 at 18:57
  • I've marked this as a duplicate of a question where the poster also had "almost 0" values and was asking for a remedy. If you want to check if something is numerically equal to 0, you could try: `all.equal(7.105427e-15, 0)`. – josliber Sep 11 '15 at 20:56
  • Okay guys, I am little confused what the problem is here. I am not trying to see if the numbers are equal to zero, I do not want to round them, I just want to add them all together and get the right answer. Can anyone provide some information into how that is done correctly, or are we going to continue with tangents and non-sequiturs? If I cant even do the sum function itself and get the correct result, how am I to know that any complex functions using _sum_ will work either? I just need to know what needs to be done so that an accurate and correct sum can be acquired from floating points. – Nick31415 Sep 13 '15 at 20:48

0 Answers0