-
Notifications
You must be signed in to change notification settings - Fork 53
/
deconstruct.js
70 lines (54 loc) · 1.97 KB
/
deconstruct.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
function deconstruct(number) {
// This function deconstructs a number, reducing it to its components:
// a sign, an integer coefficient, and an exponent, such that
// number = sign * coefficient * (2 ** exponent)
let sign = 1;
let coefficient = number;
let exponent = 0;
// Remove the sign from the coefficient.
if (coefficient < 0) {
coefficient = -coefficient;
sign = -1;
}
if (Number.isFinite(number) && number !== 0) {
// Reduce the coefficient: We can obtain the exponent by dividing the number by
// two until it goes to zero. We add the number of divisions to -1128, which is
// the exponent of 'Number.MIN_VALUE' minus the number of bits in the
// significand minus the bonus bit.
exponent = -1128;
let reduction = coefficient;
while (reduction !== 0) {
// This loop is guaranteed to reach zero. Each division will decrement the
// exponent of the reduction. When the exponent is so small that it can not
// be decremented, then the internal subnormal significand will be shifted
// right instead. Ultimately, all of the bits will be shifted out.
exponent += 1;
reduction /= 2;
}
// Reduce the exponent: When the exponent is zero, the number can be viewed
// as an integer. If the exponent is not zero, then adjust to correct the
// coefficient.
reduction = exponent;
while (reduction > 0) {
coefficient /= 2;
reduction -= 1;
}
while (reduction < 0) {
coefficient *= 2;
reduction += 1;
}
// The number's coefficient may lie outside the safe integer range, so we shift
// information into the exponent.
while (coefficient % 2 === 0 && exponent !== 0) {
coefficient /= 2;
exponent += 1;
}
}
// Return an object containing the three components and the original number.
return {
sign,
coefficient,
exponent,
number
};
}