Some problem about ceil()

13 views (last 30 days)
Edmond Dantes
Edmond Dantes on 12 Jul 2017
Commented: Edmond Dantes on 12 Jul 2017
The result of ceil(215.08/0.152) is 1416. However, it should be 1415 in practice. This makes a further mistake for the latter calculation. How can I avoid this problem?
  2 Comments
Star Strider
Star Strider on 12 Jul 2017
Your image did not appear.
Using round instead of ceil returns 1415.
Edmond Dantes
Edmond Dantes on 12 Jul 2017
Thanks for your comment. But I really need to use ceil(), also to deal with other cases. The meaning here I need is just the nearest bigger integer, not round.

Sign in to comment.

Accepted Answer

James Tursa
James Tursa on 12 Jul 2017
Edited: James Tursa on 12 Jul 2017
Yeah ... floating point arithmetic bites again:
>> num2strexact(215.08/0.152)
ans =
1.415000000000000227373675443232059478759765625e3
>> num2strexact(215080/152)
ans =
1.415e3
The trailing bits of the floating point calculation will make a difference in the result. If you need the 2nd result in your calculations, your code is not robust against these floating point differences and you will need to rewrite your code. You can see that trailing bit in the hex representation:
>> num2hex(215.08/0.152)
ans =
40961c0000000001
  11 Comments
Walter Roberson
Walter Roberson on 12 Jul 2017
sym() is slower for calculations, and a lot of the time the extra precision is not required.
Floating point operations are not transitive or distributive.
Programs that are fragile to single bit round-off are usually not designed with proper numeric error analysis and so tend to break for other reasons. Like failing to recognize that a calculation will overflow or underflow under circumstances that were thought to be handled. (If you use the gamma function, or one of the Bessel-related functions, or the ratio of factorials, or if you use a polynomial of degree higher than seven over a range outside [-1, +1], then chances are your code breaks in ways you did not plan for.)
Writing robust floating point calculations is not easy.
Edmond Dantes
Edmond Dantes on 12 Jul 2017
Thanks a lot for you all. I will use sym to solve this problem. y = ceil(sym(a)/sym(b)).

Sign in to comment.

More Answers (1)

Guillaume
Guillaume on 12 Jul 2017
As others have commented, this is normal behaviour for computers using ieee floating points. Switching to some non-binary storage system (e.g. .Net System.Decimal) is an option. Alternatively, you can round your result to something with less decimal, then use ceil on that:
ceil(round(215.08/0.152, 8))
While the above works for this particular case, I'm sure that some counterexamples could be found.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!