0

I would like to do the summation of product of all the elements of two vectors in R language, but something goes wrong. This is my data definition:

> alpha <- 1/24
> a <- c(-5, -2, 1)
> b <- c(alpha*3, alpha*2, 1-5*alpha)

Then I'm trying:

> result <- sum(a*b)
> result
[1] 8.326673e-17

And I expect the result is zero, but it's not.
To explain better, I would like to compute this summation:

(a[1]*b[1]) + (a[2]*b[2]) + (a[3]*b[3])

That should be:

(-5*alpha*3)+(-2*alpha*2)+(1*(1-alpha*5)) = (-5*1/24*3)+(-2*1/24*2)+(1*(1-5*1/24)) = 0
SnowFrog
  • 1,162
  • 4
  • 19
  • 38
glc78
  • 439
  • 1
  • 8
  • 20
  • 2
    This is simply round-off error. See [Why are these numbers not equal?](https://stackoverflow.com/q/9508518/4752675) – G5W May 03 '18 at 21:08
  • Worth noting additionally that sum(a*b) is correct syntactically, and G5W is referring to the result of 8.326673e-17 ~=~ 0. – C-x C-c May 03 '18 at 21:12
  • 2
    You can still get a zero. Maintain the values as fractions then just compute them: `b <- MASS::fractions(c(alpha*3, alpha*2, 1-5*alpha));sum(b*a)` – Onyambu May 03 '18 at 21:16
  • @Onyambu Great, it works by simply doing: `result <- fractions(sum(a*b))` – glc78 May 03 '18 at 21:24
  • Yes I know that works too – Onyambu May 03 '18 at 21:24
  • @RuiBarradas I understand, but I was also looking for a good solution to avoid the problem, as is the one suggested by Onyambu. – glc78 May 03 '18 at 21:32
  • 1
    @Glk-78 In general, rather than testing for exact equality, you test with a given tolerance. In your case, you would do something like `abs(sum(a*b)) < 1e-8` or whatever epsilon is appropriate for your use case. – Hong Ooi May 03 '18 at 21:37

0 Answers0