MATLAB: Is floor(2.00000000) giving me a result of 1

floortruncation error

Hello everyone,
I have a homework from a MOOC in which for the function I have to "dissect" the digits of a number to see if it is a palindromic number; so far I don't know of any built-in function that does that so I found a way to do it "manually" and it is actually supposed to work if floor() gives me the correct result.
I took a screenshot to post it (the greyed-out part is for the other forum), and there you can see a reproduction fo the calculations being carried out in the function for the problematic case. Why is this happening? I can't find a reason in the documentation.
What I'm doing here is taking a number—12 in this case—and creating a vector with its digits, but I can't go any further for the other digit because the first one is wrong. The variable names are not descriptive, only for me they are, but I think you can see what I'm trying to do.
Thanks in advance.

Best Answer

  • If the number is displaying as 2.0000... on the screen, it isn't exactly 2 but it is close to 2. If a number is exactly 2 it will display as 2 without the 0's past the decimal point printed. So you apparently have done some calculations that result in a number that is very slightly less than 2.
    Basically, the result of your floating point calculations cannot be represented exactly in IEEE double precision arithmetic. So this is leading to your problem. E.g., your calculations with the exact decimal conversions shown (note that 1.2 and 0.2 cannot be represented in IEEE double precision exactly):
    >> mul = 2*6
    mul =
    >> XVY = 10
    XVY =
    >> XVZ = mul/XVY
    XVZ =
    >> XVZ_1 = floor(XVZ)
    XVZ_1 =
    >> XVW = 1.2 - XVZ_1
    XVW =
    >> T1 = XVW*10
    T1 =
    2.0000 <-- 0's printing after decimal point means number is not exactly 2
    >> floor(T1)
    ans =
    >> num2strexact(XVZ)
    ans =
    >> num2strexact(XVW)
    ans =
    >> num2strexact(T1)
    ans =