weird rounding error?
Mostra commenti meno recenti
Hello. I'm getting the following odd "error" which I hope is just a display thing but really doesn't seem to be. I'm using R2016a on redhat linux.
>> format long
>> 177.5 - 170.6
ans = 6.900000000000006
>> 177.5 - 170.6 -6.9
ans = 5.329070518200751e-15
>> 1.5 - 0.6
ans = 0.900000000000000
>> 10.5 - 9.6
ans = 0.900000000000000
>> 100.5 - 99.6
ans = 0.900000000000006
>> (100.5 - 99.6) > 0.9
ans = 1
Risposta accettata
Più risposte (2)
Jason
il 21 Apr 2017
0 voti
2 Commenti
James Tursa
il 21 Apr 2017
This is not "MATLAB" behavior, per se ... it is floating point arithmetic behavior that you would encounter on any machine using binary floating point to represent the numbers. You will run into it with other languages as well.
For calculators, any particular calculator might be using binary floating point with a different number of mantissa bits, or it might be using binary coded decimal. So yes the results would not necessarily be expected to compare to MATLAB.
Roger Stafford
il 21 Apr 2017
@Jason: You should be aware of the fact that what you call “matlab behavior” is not really caused by matlab, but rather by the computer you are using to run matlab. Its floating point numbers are designed to use binary numbers, not decimal numbers, and as such it cannot represent most decimal fractions exactly. In particular it cannot represent your fractions, 99.6, 0.6, 0.9 exactly. (This is apparently due to the inefficiency in constructing electronic ten-state circuits, as opposed to two-state circuits, so you can lay the blame on computer engineers.) However, even on a truly decimal machine if you wanted to test, say, the equality
3/14 + (3/14 + 15/14) == (3/14 + 3/14) + 15/14
it is likely the computer would give “false” as its answer, and thereby violate the associative law of addition. Try it on your favorite decimal calculator. The lesson to be learned here is that one should be very cautious in using the equality test for floating point numbers, since it requires exact equality, and even a one-bit difference in the least bit will fail the test.
David Goodmanson
il 21 Apr 2017
Modificato: David Goodmanson
il 21 Apr 2017
0 voti
Yes, it's interesting that for some tasks such as addition and subtraction of quantities with a fixed number of decimal digits, a $10 calculator does a better job in a sense than does expensive scientific software. But as you alluded, one is stuck with the rules of the game.
Categorie
Scopri di più su Matrix Indexing in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!