3

I have a problem with the ceil function in matlab. When I say "ceil(192.00)" it returns 192, as it should. However, when I declare a variable x and assign it 14*(256/20)+(256/20), that being exactly 192.00, ceil(x) returns 193. Why is that? Thanks in advance!

Vlad Iordache
  • 468
  • 1
  • 5
  • 16

2 Answers2

4

This is due floating point arithmetic in MATLAB (more info here). As you have pointed out, the value appears to be 192.00, but what you haven't shown are all of the digits after the decimal point. If you compare your value to the integer 192, you will see that it is in fact just larger than 192. The difference is due to the floating point arithmetic errors.

x = 14 * (256 / 20) + (256 / 20);
x - 192

    2.8421709430404e-14

If we use the technique mentioned by Daniel in the comments, we can actually see the true value of x to verify that it in fact is greater than 192.

num2str(x, 17)

    192.00000000000003

Or for the sake of ridiculousness

num2str(x, 48)

    192.000000000000028421709430404007434844970703125

Because it is slightly higher, it is then going to be rounded up to 193 by ceil.

If you want a little bit of flexibility in ceil, you could always subtract a small epsilon from your number prior to performing ceil. This will allow for some floating point errors and give you the result you expect.

tolerance = 1e-12
ceil(x - tolerance)

    192
Community
  • 1
  • 1
Suever
  • 64,497
  • 14
  • 82
  • 101
  • Changed format, it still shows no decimals. I checked with another number that could not be integer, and I saw 12 decimals, but my number is exactly 192. – Vlad Iordache Mar 23 '16 at 23:21
  • 1
    @Vlad Iordache:[Format long is not sufficient, you need 17 digits](http://stackoverflow.com/questions/35624419/matlab-vs-c-double-precision/35626253#35626253). The result is `192.00000000000003` – Daniel Mar 23 '16 at 23:24
  • 1
    @Daniel Thanks for linking that! I have been wondering how to get more digits to display. – Suever Mar 23 '16 at 23:25
0

I faced the same problem, my original bug is:

ceil(168*1.55/1.55)

ans = 

169

I resolve this problem by subtracting a small number

ceil(168*1.55/1.55 - 0.001)

Pay attention, it's better to do subtraction after a bunch of calculation

ceil(168*1.55/1.55 - 0.001)

If you subtract in the middle of the calculation, you may still get wrong number. Like. (168 is my variable place, it would be better not changing the varialble)

ceil((168-0.00000000000001)*1.55/1.55)
Albert Chen
  • 1,331
  • 1
  • 12
  • 13