Problem when testing long decimal numbers
5 views (last 30 days)
Show older comments
I generated a set of numbers (integers and long decimals) and I tested them are they integers or not.
e.g., when I tested the number 2.00000000000000000000000000095861, I write
>> mod(2.00000000000000000000000000095861,1)
ans =
0
i.e., the number 2.00000000000000000000000000095861 is integer. Althought, it is decimal.
Note: The same problem occurs when using Floor function for testing the long decimal number is it integer or not.
What is the problem? I appreciate your help.
0 Comments
Accepted Answer
John D'Errico
on 4 Jul 2021
Edited: John D'Errico
on 4 Jul 2021
The problem is merely your understanding of floating point numbers and the methods used to store them.
MATLAB uses only 52 binary bits of precision to store a floating point number.
What would it require to store that number?
log2(str2sym('2.00000000000000000000000000095861') - 2)
So 100 binary bits would just barely suffice to approximate that number, but not that closely. And as I said, MATLAB stores a floating point number as a DOUBLE, thus only 52 binary bits. There is no 16 byte floating point class, and even that would probably be barely sufficient. And of course, if you had such a long precision form available, we would constantly see questions just like yours...
"Why won't MATLAB exactly represent this number?
2.00000000000000000000000000000000000000000000000000000000000000095861
The answer is to understand how a number is stored and how to work with that. This sometimes requires a good grounding in numerical methods.
0 Comments
More Answers (0)
See Also
Categories
Find more on NaNs 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!