Incorrect calculation subtracting numeric values stored in a cell array
Show older comments
I'm performing a simple subtraction in Matlab. Both values are stored in a cell array (I'm using numerics and strings).
prices{2,1}{848,5} has the numeric value 4.7903, and prices{2,1}{847,5} has the numeric value 4.7586
my calculation is: prices{2,1}{848,5} - prices{2,1}{847,5}
i.e. 4.7903 - 4.7586.
The correct answer should be 0.0317 but Matlab returns 0.0318. I have used cell2mat function but still no joy.
I've tested it on different versions of Matlab on diferent machines using the same data and get the same error.
If I type in the values as a=4.7903 and b=4.7586 and then type c = a-b then I get the correct answer.
So it must be something to do with using cell arrays.
Any ideas?
Accepted Answer
More Answers (1)
Christian
on 17 Nov 2014
0 votes
1 Comment
John D'Errico
on 18 Nov 2014
In fact, 0.318 is not the correct answer, since o.318 is not stored exactly in floating point as a double. Were you to try to stuff 0.318 in a double, in fact, MATLAB would store it as
0.031800000000000001876276911616514553315937519073486328125
This is as close as a number stored in BINARY, using a 52 bit mantissa in the IEEE representation can come to 0.0318. Shift the least significant bit by just a nibble, and it looks like you get...
0.031799999999999994937383007709286175668239593505859375
But no, there is nothing sinister here, just life in the wacky world of floating point arithmetic.
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!