Does anybody know why the ceil()-function Returns two different values in the following case?
X=[4 (1-0.95)*80]; ceil(X)
ans =
4 5
Thank you!
Best Answer
Floating point numbers are how decimal values are stored in your computer: they do not have infinite precision, and they can only approximate many values. Even if itlooks like the "actual" value is being shown to you this does not mean that the internal representation inside your computer is the same value.
Lets have a quick look at those values:
>> X=[4 (1-0.95)*80]
X =
4.0000 4.0000
>> fprintf('%.30f\n',X)
4.000000000000000000000000000000
4.000000000000003552713678800501
It is not a problem with MATLAB, this is simply how (binary) computers work.
"Why will round() not work on this number for 4 decimal places?"
It does work. It rounds to the nearest floating point number.
"Found an unepected behavior for round..."
Rounding to the nearest floating point numberis the expected behavior (and is really the onlypossible behavior if working only withdouble numbers).
"Can anyone explain what's going on here?"
The value that you are trying to round to cannot be exactly represented using binary floating point numbers. What you see printed in the command window is the closestrepresentation to 16 significant digits.KALYAN ACHARJYA's answer shows the closestrepresentation to 5 significant digits. Neither of theserepresentations is more correct than the other, they are just the same floating point number displayed to different precisions. Neither of them is the "real" value. To see the "real" value download James Tursa's FEX submission:
Use James Tursa'snum2strexact and you will see that none of your "expected" values really have the values that you think they do (unless they are powers of two). All you are looking at is arepresentation of those floating point numbers displayed in the command window, to the precision defined by yourformat setting. Just because you see0.1000 displayed tells you nothing about the "real" floating point number's value.
Note that you can change how the value isdisplayed by changing theformat. This is the only difference between KALYAN ACHARJYA's answer and your question.
You need to learn about the limits of floating point numbers. Start by reading these:
You can't use ceil(end/2). Even though the result of ceil is going to be used as an index, that index cannot be created from ceil(end/2) because it doesn't know what "end" is, even though you might think it should since the "end" is also inside a matrix reference. To fix, replace "end" by something, like size(MAGIC2, 1) or 3 or something:
Best Answer