Can someone please help me understand why -1 + 1 <> 0 ?
Can someone please help me understand why I get three different values between the built-in function consum(), my function ct(), and Excel when they are all doing the same thing?
Now, I'm pretty sure the answer is a 'round' issue, but I can't figure out where that part of this issue is coming from. I mean, this all 'seems pretty straight forward.
In R, when I build the sequence 'a' and then run cumsum(a) I don't get the result of 0 like I expect to get. I also get a different answer if I try to calculate the same value using a function. Finally, I get a third answer if I try to calculate the same value using Excel.
This is what I get using cumsum():
> a<- seq(-1, 1, by=.1)
> a
[1] -1.0 -0.9 -0.8 -0.7 -0.6 -0.5 -0.4 -0.3 -0.2 -0.1 0.0 0.1 0.2 0.3
[15] 0.4 0.5 0.6 0.7 0.8 0.9 1.0
> cumsum(a)
[1] -1.000000e+00 -1.900000e+00 -2.700000e+00 -3.400000e+00 -4.000000e+00
[6] -4.500000e+00 -4.900000e+00 -5.200000e+00 -5.400000e+00 -5.500000e+00
[11] -5.500000e+00 -5.400000e+00 -5.200000e+00 -4.900000e+00 -4.500000e+00
[16] -4.000000e+00 -3.400000e+00 -2.700000e+00 -1.900000e+00 -1.000000e+00
[21] 1.110223e-15
I wrote a quick function to test this and expected to get the same answer (or 0), but I get a totally different answer. Here is my function with its results:
ct<- function(x){
result = 0
for(i in 1:length(x)){
cat(i, ": Result = ", result, " + ", x[i], " = ", result + x[i], "\n")
result = result + x[i]
}
}
> ct(a)
1 : Result = 0 + -1 = -1
2 : Result = -1 + -0.9 = -1.9
3 : Result = -1.9 + -0.8 = -2.7
4 : Result = -2.7 + -0.7 = -3.4
5 : Result = -3.4 + -0.6 = -4
6 : Result = -4 + -0.5 = -4.5
7 : Result = -4.5 + -0.4 = -4.9
8 : Result = -4.9 + -0.3 = -5.2
9 : Result = -5.2 + -0.2 = -5.4
10 : Result = -5.4 + -0.1 = -5.5
11 : Result = -5.5 + 0 = -5.5
12 : Result = -5.5 + 0.1 = -5.4
13 : Result = -5.4 + 0.2 = -5.2
14 : Result = -5.2 + 0.3 = -4.9
15 : Result = -4.9 + 0.4 = -4.5
16 : Result = -4.5 + 0.5 = -4
17 : Result = -4 + 0.6 = -3.4
18 : Result = -3.4 + 0.7 = -2.7
19 : Result = -2.7 + 0.8 = -1.9
20 : Result = -1.9 + 0.9 = -1
21 : Result = -1 + 1 = 4.440892e-16
If I change the last line in the for loop to this, then I get the expected answer of 0:
result = round(result + x[I], digits = 2)
In Excel, using the same logic as in my ct() function, I get a final result of -2.886580E-15 (without rounding the values).