javascript - Math.log() inaccuracy - How to deal with it? -
this question has answer here:
- is floating point math broken? 20 answers
i know getting 10 based logarithm have use math.log() divided constant of natural logarithm of 10.
var e1000 = math.log(1000) / math.ln10; // result: 2.9999999999999996 instead of // expected 3. console.log(e1000); // result: 999.999999999999 instead of // expected 1000. console.log(math.pow(10, e1000));
but: result approximation. if use calculated value in further calculation inaccuracy becomes worse.
am doing wrong? there more elegant way around using math.ceil()?
the floating point rounding difference known , coincidentally 2.9999 exact example used in mdn math.log page. mentioned math.ceiling
can used alther result. likewise increase base number , use smaller divider decrease change of floating errors. e.g.
function log10(value){ return -3 * (math.log(value * 100) / math.log(0.001)) - 2; }
example: fiddle
as sidenote, browsers support math.log10 functionality, extend math
use function above if not implemented with:
if (!math.log10) math.log10 = function(value){ return -3 * (math.log(value * 100) / math.log(0.001)) - 2; };
after running initializer, can use math.log10()
, code automatically use browser functionality (or when becomes) available. (fiddle)
Comments
Post a Comment