Some problem about ceil()
조회 수: 13 (최근 30일)
이전 댓글 표시
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
채택된 답변
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
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.
추가 답변 (1개)
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.
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!