1

I have a vector of data and I want to 'manually' calculate variance and standard deviation.

pointsPerGame<-c(28,26,10,27,20,38,23,28,25,2)

I can get the deviation scores like this

pointsPerGame - mean(pointsPerGame)

But when I try to get the sum of the deviation scores it won't sum to zero like it should.

deviationScores<- pointsPerGame - mean(pointsPerGame)
sum(deviationScores)

I know this has to do with the level of precision in R, but I don't know how to prevent it from doing so for my purposes.

Hope you can help.

This question has been flagged as an answer to my question Why are these numbers not equal? But I want R to display 0 for teaching purposes, it'd be extremely confusing to get into the details of floating points etc.

Community
  • 1
  • 1
adkane
  • 1,429
  • 14
  • 29

1 Answers1

2

You figured out the answer already; you just have to accept that you are an analyst and a part-time computer scientist now. Floating point arithmetic is with you unless you prefer the allure of Excel.

all.equal(0L, sum(deviationScores))
[1] TRUE

Edit

For teaching purposes, to show 0 for the sum.

devsum <- sum(deviationScores)
devsum <- if(all.equal(0L, devsum)) 0L else devsum
Pierre L
  • 28,203
  • 6
  • 47
  • 69