Math.log () error - how to deal with it?

I know that to get the 10-based logarithm, I have to use Math.log () divided by the natural logarithm constant 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: The result is just an approximation. If I use the calculated value in further calculations, the error gets worse.

Am I doing something wrong? Is there a more elegant way around it, just using Math.ceil ()?

+3


source to share


1 answer


The floating point rounding difference is known and the 2.9999 match is the exact example used on the MDN Math.Log page . As you mentioned, Math.ceiling

can be used to get the result. Likewise, you can increase the base number and use a smaller divisor to reduce the variation in floating errors. eg.

function log10(value){
  return -3 * (Math.log(value * 100)  / Math.log(0.001))  - 2;
}

      

Example: violin



As a side element, some browsers already support the Math functionality. log10 , you can extend Math

to use the above function if not implemented with:

if (!Math.log10) Math.log10 = function(value){
  return -3 * (Math.log(value * 100)  / Math.log(0.001))  - 2;
};

      

Once this initializer is run, you can simply use Math.log10()

and your code will automatically use browser functions wherever it is (or when it becomes) available. ( violin )

+1


source







All Articles