Background: I am reading "How Numbers Work" in the book How JavaScript Works by Douglas Crockford.
A number in JavaScript is represented as number = sign * coefficient * (2 ** exponent)
. I understand this but then there is a function deconstruct
to represent an integer using the sign
, coefficient
, and exponent
.
In order to find the exponent
, the initial value is taken as -1128
which is the exponent of 'Number.MIN_VALUE' minus the number of bits in the significand minus the bonus bit.
function deconstruct(number) {
// .....
exponent = -1128;
let reduction = coefficient;
while (reduction !== 0) {
// .....
}
Why is exponent = -1128
? I did not get the reason for starting with this number, please help me in understanding this.
The complete deconstruct function as mentioned in the book.
A similar question is asked here but I did not understand the answer.
I think Crockford chose this value so that the resulting
coefficient
is always a 53-bit integer.The
deconstruct
function determines the exponent by repeatedly dividing by two, and counting how long it takes to reach0
. For the number1
, which has an exponent of0
(for a coefficient of1.0
), it takes 1075 steps, so by starting at-1075
and counting up we'd arrive at the exponent of0
. However, to get the long coefficient, we want to arrive at an exponent of-53
, so we have to start at-1128
already.Another way to put it:
Number.MIN_VALUE
, which is1 * 2**-1074
, needs to be multiplied by 2 1074 times to arrive at 1, then some more times to get the long coefficient.Notice there are multiple off-by-one mistakes to be made here:
1
(a 1-bit integer) as a 53-bit integer, we need an exponent of-52
not-53
0
1
bit (for normal numbers)And Crockford actually made one of them! If you check out the maths, 1074 (exponent of
MIN_VALUE
) + 52 (significand binary digits) + 1 ("bonus bit", whatever that refers to) amounts to 1127, not 1128. Calling thedeconstruct
function will return a.coefficient
with 54 binary digits, which is one too many.That said, I think even the goal is questionable. Having the coefficient, which is actually a fractional number starting with
1.…
, represented as an integer may be excused as a teaching device for the book. But it doesn't make any sense to represent subnormal numbers (whose coefficients are fractional numbers0.…
) as numbers larger than 252, with barely any significant digits.