Some problem about ceil()

조회 수: 13 (최근 30일)
Edmond Dantes
Edmond Dantes 2017년 7월 12일
댓글: Edmond Dantes 2017년 7월 12일
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
Star Strider
Star Strider 2017년 7월 12일
Your image did not appear.
Using round instead of ceil returns 1415.
Edmond Dantes
Edmond Dantes 2017년 7월 12일
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.

댓글을 달려면 로그인하십시오.

채택된 답변

James Tursa
James Tursa 2017년 7월 12일
편집: James Tursa 2017년 7월 12일
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
Walter Roberson
Walter Roberson 2017년 7월 12일
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 2017년 7월 12일
Thanks a lot for you all. I will use sym to solve this problem. y = ceil(sym(a)/sym(b)).

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Guillaume
Guillaume 2017년 7월 12일
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!