Why does Matlab add digits to a code generated vector?
3 views (last 30 days)
I have a simple command that is creating a vector. Test = (51.7:.1:130)' I then iterate through this vector and use the values to search in a list of data that I have. What I find, is that Matlab is actually adding very small numbers to the end of some of my values. For instance 65.5 truly equals 65.500000... However, 65.6 (when you double click) equals 65.600000000000010
I can not think of a logical reason for this behavior. Now, I certainly can go ahead and round the vector before I loop, but that shouldn't be necessary. I'd like to understand why it can't create the vector that I specified.
Thanks for your help, Brian
Star Strider on 19 Oct 2015
There are two separate processes involved: floating-point approximation error, and the way MATLAB calculated colon-operator generated vectors. If you only want the vector elements to be defined at one decimal place, multiply the vector by 10, use round, floor, or fix, and then divide it by 10:
Test = round(Test*10)/10;
That should provide you with reasonably precise values for your comparison.