2

There is an interesting question on Facebook which I encountered. He asks that he is using MATLAB R2014a (64-bit version) and ran this code:-

x = 0.45;
min = fix((x)*60);
fprintf('min = %d \n', min);

x = 20.45
min = fix((x-20)*60);
fprintf('min = %d \n', min);

The results are following:

>> tx
min = 27
min = 26

which are incorrect because (20.45 - 20) should give the same result as 0.45, but it does not.

He also attempted %f but it still gave the same result.

At first, I thought it was problem with storing floating point but after I calculated it, it did not seem to be the right answer.

So, I think this question is interesting and challenging. Could anyone please help me explain how this happens?

Where the answers are not equal.

Thanks!

Thammarith
  • 662
  • 5
  • 19
  • 3
    Yes, it is an error from storing floating point . `0.45` is not `20.45-20` – Ander Biguri Mar 29 '16 at 13:43
  • 2
    Useful lecture: https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – liori Mar 29 '16 at 13:43
  • 5
    The closest double to 0.45 is 0.450000000000000011102230246251565404236316680908203125, slightly larger than exact. The closest double to 20.45 is 20.449999999999999289457264239899814128875732421875, slightly smaller than exact. 20.45-20 evaluates to 0.449999999999999289457264239899814128875732421875 – Patricia Shanahan Mar 29 '16 at 13:45
  • 3
    Bsically, someone designed that code to confuse you ;) – Ander Biguri Mar 29 '16 at 13:46
  • @PatriciaShanahan Great! May I know how you calculated that? I need to try with other numbers. Thanks for that. – Thammarith Mar 29 '16 at 14:29
  • @Thammarith I used Java's exact conversion of double to BigDecimal, and exact BigDecimal toString. There are also web sites such as [Decimal to Floating-Point Converter](http://www.exploringbinary.com/floating-point-converter/). Many languages, by default, display a shorter approximation rather than the exact value of a float or double. – Patricia Shanahan Mar 29 '16 at 15:18

1 Answers1

2

The problem you are seeing is to do with storing floating point numbers, see:

20.45-20==0.45

When you do the calculation in your head it comes out the same, but in the computer it doesn't see this question for more details

Community
  • 1
  • 1
matlabgui
  • 5,642
  • 1
  • 12
  • 15