Incorrect calculation subtracting numeric values stored in a cell array
显示 更早的评论
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?
采纳的回答
更多回答(1 个)
Christian
2014-11-17
0 个投票
1 个评论
John D'Errico
2014-11-18
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.
类别
在 帮助中心 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!