MATLAB Answers

Why does Matlab add digits to a code generated vector?

2 views (last 30 days)
Brian
Brian on 19 Oct 2015
Commented: Star Strider on 19 Oct 2015
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

Accepted Answer

Star Strider
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.
  3 Comments
Star Strider
Star Strider on 19 Oct 2015
My pleasure.
The floating point approximation error arises in having to represent a decimal number as a string of bits. It’s somewhat analogous to representing 1/3 in decimal digits. The fraction is precise, the decimal approximation, 0.333... with any finite length will never will exactly be equal to the fraction. (In the real world, such word-lengths are finite.) The documentation on Accuracy of Floating Point Data discusses this.
There was a post here a bit ago (that I now cannot locate) that described that MATLAB creates its colon-operator vectors by beginning at each end, adds the step from the beginning of the vector and subtracts it from the end, meeting at the centre of the vector so as to minimise the propagation of errors that would otherwise result if the vector was generated from only one end.
You’re correct to wonder about the ‘simplicity’ of such an instruction, but in the real world applications, things are rarely as simple as they might appear.

Sign in to comment.

More Answers (0)

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by