Search code examples
javascriptnumbersinequality

Javascript numbers representing limits of inequality comparisons


I am working with a set of values such that 0 < value < 1. I want to validate some data such that a value outside this range is modified to the closest valid value. After some experimentation, I discovered Number.MIN_VALUE as the best way of representing the lower limit. However, the upper limit, 1 - Number.MIN_VALUE, has unexpected behaviour:

Whereas:

Number.MIN_VALUE; //5e-324 and Number.MIN_VALUE > 0; //true

1 - Number.MIN_VALUE; //1 and 1 - Number.MIN_VALUE < 1; //false

So, what is the best way of generating the smallest and largest numbers in Javascript that satisfy an inequality of the form a < value < b?


Solution

  • The mantissa of a JavaScript float has 52 bits. With denormalization, the minimum float can be extremely small, 5e-324 -- this is represented as something like 51 zero bits, 1 one bit, and the most negative exponent.

    But you can't get that close to 1, because the representation of this will be all one bits, and you can't increase the range using exponents. It's limited by the floating point precision.

    So the value will be as given below:

    console.log(1 - .5**53);