Javascript for loop doing bad math -


this question has answer here:

does know how core, fundamental functionality of programming language can lose ability calculations properly/precisely?

http://jsfiddle.net/krazyjakee/v3xcq/

var html = ''; for(var = 0; <= 1; += 0.01){      html += + '<br />'; } document.body.innerhtml = html; 

my question why happen , how can stop happening?

0 0.01 0.02 0.03 0.04 0.05 0.060000000000000005 0.07 0.08 0.09 0.09999999999999999 0.10999999999999999 

why don’t numbers, 0.1 + 0.2 add nice round 0.3, , instead weird result 0.30000000000000004?

because internally, computers use format (binary floating-point) cannot accurately represent number 0.1, 0.2 or 0.3 @ all.

when code compiled or interpreted, “0.1” rounded nearest number in format, results in small rounding error before calculation happens.

why computers use such stupid system?

it’s not stupid, different. decimal numbers cannot accurately represent number 1/3, have round 0.33 - , don’t expect 0.33 + 0.33 + 0.33 add 1, either - you?

computers use binary numbers because they’re faster @ dealing those, , because calculations, tiny error in 17th decimal place doesn’t matter @ since numbers work aren’t round (or precise) anyway.

what can avoid problem?

that depends on kind of calculations you’re doing.

if need results add exactly, when work money: use special decimal datatype. if don’t want see decimal places: format result rounded fixed number of decimal places when displaying it. if have no decimal datatype available, alternative work integers, e.g. money calculations entirely in cents. more work , has drawbacks. why other calculations 0.1 + 0.4 work correctly?

in case, result (0.5) can represented floating-point number, , it’s possible rounding errors in input numbers cancel each other out - can’t relied upon (e.g. when 2 numbers stored in differently sized floating point representations first, rounding errors might not offset each other).

in other cases 0.1 + 0.3, result isn’t 0.4, close enough 0.4 shortest number closer result other floating-point number. many languages display number instead of converting actual result closest decimal fraction.


Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -