Make your JS programs precise
Objective: To make sure the arithmetics are as precise as possible. I recently encountered a mathematical question where I needed to figure out if a number(n) can be expressed as A^x.
My theory was if a log of a number was divisible by the log of any number less than square root (optimization for loop) then that number could theoretically be expressed as A^x. Note we just have to figure out if it’s of proper form or not and not the actual A and x values. Easy then,
Approach:
Loop from 2 => sqrt(n) {
if(isInteger(log(n)/log(i))){return 'yessss'}
}
return false;
Alright, this should work. The base case passed however the submission failed at a large number. When something like this happens it’s a high chance the high precision values are not being handled properly. And the culprit is usually near the arithmetic operator. After dry running on a sample value, i was getting 3.000000004. Which was not an integer technically but was since it was a JS number precision issue.
Enter Number. Epsilon: The Number.EPSILON
this property represents the difference between 1 and the smallest floating-point number greater than 1. We can also use this in a way to eliminate the precision issue using this formula.
Number.isInteger(Math.round(( PRECISIE_NUMBER) + Number.EPSILON) * 10^N) / 10^N)
//N -> is the precision level you want
// PRECISE_NUMBER -> number that's having rounding issues
And voila! Perfect precise and rounded till the decimal I want. Bonus leetcode result.
Happy Coding!!