Some problem about ceil()
13 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Edmond Dantes
il 12 Lug 2017
Commentato: Edmond Dantes
il 12 Lug 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 Commenti
Risposta accettata
James Tursa
il 12 Lug 2017
Modificato: James Tursa
il 12 Lug 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 Commenti
Walter Roberson
il 12 Lug 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.
Più risposte (1)
Guillaume
il 12 Lug 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.
0 Commenti
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!