Reputation: 528
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!
Upvotes: 3
Views: 337
Reputation: 1391
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)
Upvotes: 0
Reputation: 65430
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
Upvotes: 4