deps: update v8 to 4.3.61.21
[platform/upstream/nodejs.git] / deps / v8 / src / third_party / fdlibm / fdlibm.js
1 // The following is adapted from fdlibm (http://www.netlib.org/fdlibm),
2 //
3 // ====================================================
4 // Copyright (C) 1993-2004 by Sun Microsystems, Inc. All rights reserved.
5 //
6 // Developed at SunSoft, a Sun Microsystems, Inc. business.
7 // Permission to use, copy, modify, and distribute this
8 // software is freely granted, provided that this notice
9 // is preserved.
10 // ====================================================
11 //
12 // The original source code covered by the above license above has been
13 // modified significantly by Google Inc.
14 // Copyright 2014 the V8 project authors. All rights reserved.
15 //
16 // The following is a straightforward translation of fdlibm routines
17 // by Raymond Toy (rtoy@google.com).
18
19 // Double constants that do not have empty lower 32 bits are found in fdlibm.cc
20 // and exposed through kMath as typed array. We assume the compiler to convert
21 // from decimal to binary accurately enough to produce the intended values.
22 // kMath is initialized to a Float64Array during genesis and not writable.
23 // rempio2result is used as a container for return values of %RemPiO2. It is
24 // initialized to a two-element Float64Array during genesis.
25
26 var kMath;
27 var rempio2result;
28
29 (function() {
30   
31 "use strict";
32
33 %CheckIsBootstrapping();
34
35 var GlobalMath = global.Math;
36 var GlobalArray = global.Array;
37
38 //-------------------------------------------------------------------
39
40 const INVPIO2 = kMath[0];
41 const PIO2_1  = kMath[1];
42 const PIO2_1T = kMath[2];
43 const PIO2_2  = kMath[3];
44 const PIO2_2T = kMath[4];
45 const PIO2_3  = kMath[5];
46 const PIO2_3T = kMath[6];
47 const PIO4    = kMath[32];
48 const PIO4LO  = kMath[33];
49
50 // Compute k and r such that x - k*pi/2 = r where |r| < pi/4. For
51 // precision, r is returned as two values y0 and y1 such that r = y0 + y1
52 // to more than double precision.
53
54 macro REMPIO2(X)
55   var n, y0, y1;
56   var hx = %_DoubleHi(X);
57   var ix = hx & 0x7fffffff;
58
59   if (ix < 0x4002d97c) {
60     // |X| ~< 3*pi/4, special case with n = +/- 1
61     if (hx > 0) {
62       var z = X - PIO2_1;
63       if (ix != 0x3ff921fb) {
64         // 33+53 bit pi is good enough
65         y0 = z - PIO2_1T;
66         y1 = (z - y0) - PIO2_1T;
67       } else {
68         // near pi/2, use 33+33+53 bit pi
69         z -= PIO2_2;
70         y0 = z - PIO2_2T;
71         y1 = (z - y0) - PIO2_2T;
72       }
73       n = 1;
74     } else {
75       // Negative X
76       var z = X + PIO2_1;
77       if (ix != 0x3ff921fb) {
78         // 33+53 bit pi is good enough
79         y0 = z + PIO2_1T;
80         y1 = (z - y0) + PIO2_1T;
81       } else {
82         // near pi/2, use 33+33+53 bit pi
83         z += PIO2_2;
84         y0 = z + PIO2_2T;
85         y1 = (z - y0) + PIO2_2T;
86       }
87       n = -1;
88     }
89   } else if (ix <= 0x413921fb) {
90     // |X| ~<= 2^19*(pi/2), medium size
91     var t = $abs(X);
92     n = (t * INVPIO2 + 0.5) | 0;
93     var r = t - n * PIO2_1;
94     var w = n * PIO2_1T;
95     // First round good to 85 bit
96     y0 = r - w;
97     if (ix - (%_DoubleHi(y0) & 0x7ff00000) > 0x1000000) {
98       // 2nd iteration needed, good to 118
99       t = r;
100       w = n * PIO2_2;
101       r = t - w;
102       w = n * PIO2_2T - ((t - r) - w);
103       y0 = r - w;
104       if (ix - (%_DoubleHi(y0) & 0x7ff00000) > 0x3100000) {
105         // 3rd iteration needed. 151 bits accuracy
106         t = r;
107         w = n * PIO2_3;
108         r = t - w;
109         w = n * PIO2_3T - ((t - r) - w);
110         y0 = r - w;
111       }
112     }
113     y1 = (r - y0) - w;
114     if (hx < 0) {
115       n = -n;
116       y0 = -y0;
117       y1 = -y1;
118     }
119   } else {
120     // Need to do full Payne-Hanek reduction here.
121     n = %RemPiO2(X, rempio2result);
122     y0 = rempio2result[0];
123     y1 = rempio2result[1];
124   }
125 endmacro
126
127
128 // __kernel_sin(X, Y, IY)
129 // kernel sin function on [-pi/4, pi/4], pi/4 ~ 0.7854
130 // Input X is assumed to be bounded by ~pi/4 in magnitude.
131 // Input Y is the tail of X so that x = X + Y.
132 //
133 // Algorithm
134 //  1. Since ieee_sin(-x) = -ieee_sin(x), we need only to consider positive x.
135 //  2. ieee_sin(x) is approximated by a polynomial of degree 13 on
136 //     [0,pi/4]
137 //                           3            13
138 //          sin(x) ~ x + S1*x + ... + S6*x
139 //     where
140 //
141 //    |ieee_sin(x)    2     4     6     8     10     12  |     -58
142 //    |----- - (1+S1*x +S2*x +S3*x +S4*x +S5*x  +S6*x   )| <= 2
143 //    |  x                                               |
144 //
145 //  3. ieee_sin(X+Y) = ieee_sin(X) + sin'(X')*Y
146 //              ~ ieee_sin(X) + (1-X*X/2)*Y
147 //     For better accuracy, let
148 //               3      2      2      2      2
149 //          r = X *(S2+X *(S3+X *(S4+X *(S5+X *S6))))
150 //     then                   3    2
151 //          sin(x) = X + (S1*X + (X *(r-Y/2)+Y))
152 //
153 const S1 = -1.66666666666666324348e-01;
154 const S2 = 8.33333333332248946124e-03;
155 const S3 = -1.98412698298579493134e-04;
156 const S4 = 2.75573137070700676789e-06;
157 const S5 = -2.50507602534068634195e-08;
158 const S6 = 1.58969099521155010221e-10;
159
160 macro RETURN_KERNELSIN(X, Y, SIGN)
161   var z = X * X;
162   var v = z * X;
163   var r = S2 + z * (S3 + z * (S4 + z * (S5 + z * S6)));
164   return (X - ((z * (0.5 * Y - v * r) - Y) - v * S1)) SIGN;
165 endmacro
166
167 // __kernel_cos(X, Y)
168 // kernel cos function on [-pi/4, pi/4], pi/4 ~ 0.785398164
169 // Input X is assumed to be bounded by ~pi/4 in magnitude.
170 // Input Y is the tail of X so that x = X + Y.
171 //
172 // Algorithm
173 //  1. Since ieee_cos(-x) = ieee_cos(x), we need only to consider positive x.
174 //  2. ieee_cos(x) is approximated by a polynomial of degree 14 on
175 //     [0,pi/4]
176 //                                   4            14
177 //          cos(x) ~ 1 - x*x/2 + C1*x + ... + C6*x
178 //     where the remez error is
179 //
180 //  |                   2     4     6     8     10    12     14 |     -58
181 //  |ieee_cos(x)-(1-.5*x +C1*x +C2*x +C3*x +C4*x +C5*x  +C6*x  )| <= 2
182 //  |                                                           |
183 //
184 //                 4     6     8     10    12     14
185 //  3. let r = C1*x +C2*x +C3*x +C4*x +C5*x  +C6*x  , then
186 //         ieee_cos(x) = 1 - x*x/2 + r
187 //     since ieee_cos(X+Y) ~ ieee_cos(X) - ieee_sin(X)*Y
188 //                    ~ ieee_cos(X) - X*Y,
189 //     a correction term is necessary in ieee_cos(x) and hence
190 //         cos(X+Y) = 1 - (X*X/2 - (r - X*Y))
191 //     For better accuracy when x > 0.3, let qx = |x|/4 with
192 //     the last 32 bits mask off, and if x > 0.78125, let qx = 0.28125.
193 //     Then
194 //         cos(X+Y) = (1-qx) - ((X*X/2-qx) - (r-X*Y)).
195 //     Note that 1-qx and (X*X/2-qx) is EXACT here, and the
196 //     magnitude of the latter is at least a quarter of X*X/2,
197 //     thus, reducing the rounding error in the subtraction.
198 //
199 const C1 = 4.16666666666666019037e-02;
200 const C2 = -1.38888888888741095749e-03;
201 const C3 = 2.48015872894767294178e-05;
202 const C4 = -2.75573143513906633035e-07;
203 const C5 = 2.08757232129817482790e-09;
204 const C6 = -1.13596475577881948265e-11;
205
206 macro RETURN_KERNELCOS(X, Y, SIGN)
207   var ix = %_DoubleHi(X) & 0x7fffffff;
208   var z = X * X;
209   var r = z * (C1 + z * (C2 + z * (C3 + z * (C4 + z * (C5 + z * C6)))));
210   if (ix < 0x3fd33333) {  // |x| ~< 0.3
211     return (1 - (0.5 * z - (z * r - X * Y))) SIGN;
212   } else {
213     var qx;
214     if (ix > 0x3fe90000) {  // |x| > 0.78125
215       qx = 0.28125;
216     } else {
217       qx = %_ConstructDouble(%_DoubleHi(0.25 * X), 0);
218     }
219     var hz = 0.5 * z - qx;
220     return (1 - qx - (hz - (z * r - X * Y))) SIGN;
221   }
222 endmacro
223
224
225 // kernel tan function on [-pi/4, pi/4], pi/4 ~ 0.7854
226 // Input x is assumed to be bounded by ~pi/4 in magnitude.
227 // Input y is the tail of x.
228 // Input k indicates whether ieee_tan (if k = 1) or -1/tan (if k = -1)
229 // is returned.
230 //
231 // Algorithm
232 //  1. Since ieee_tan(-x) = -ieee_tan(x), we need only to consider positive x.
233 //  2. if x < 2^-28 (hx<0x3e300000 0), return x with inexact if x!=0.
234 //  3. ieee_tan(x) is approximated by a odd polynomial of degree 27 on
235 //     [0,0.67434]
236 //                           3             27
237 //          tan(x) ~ x + T1*x + ... + T13*x
238 //     where
239 //
240 //     |ieee_tan(x)    2     4            26   |     -59.2
241 //     |----- - (1+T1*x +T2*x +.... +T13*x    )| <= 2
242 //     |  x                                    |
243 //
244 //     Note: ieee_tan(x+y) = ieee_tan(x) + tan'(x)*y
245 //                    ~ ieee_tan(x) + (1+x*x)*y
246 //     Therefore, for better accuracy in computing ieee_tan(x+y), let
247 //               3      2      2       2       2
248 //          r = x *(T2+x *(T3+x *(...+x *(T12+x *T13))))
249 //     then
250 //                              3    2
251 //          tan(x+y) = x + (T1*x + (x *(r+y)+y))
252 //
253 //  4. For x in [0.67434,pi/4],  let y = pi/4 - x, then
254 //          tan(x) = ieee_tan(pi/4-y) = (1-ieee_tan(y))/(1+ieee_tan(y))
255 //                 = 1 - 2*(ieee_tan(y) - (ieee_tan(y)^2)/(1+ieee_tan(y)))
256 //
257 // Set returnTan to 1 for tan; -1 for cot.  Anything else is illegal
258 // and will cause incorrect results.
259 //
260 macro KTAN(x)
261 kMath[19+x]
262 endmacro
263
264 function KernelTan(x, y, returnTan) {
265   var z;
266   var w;
267   var hx = %_DoubleHi(x);
268   var ix = hx & 0x7fffffff;
269
270   if (ix < 0x3e300000) {  // |x| < 2^-28
271     if (((ix | %_DoubleLo(x)) | (returnTan + 1)) == 0) {
272       // x == 0 && returnTan = -1
273       return 1 / $abs(x);
274     } else {
275       if (returnTan == 1) {
276         return x;
277       } else {
278         // Compute -1/(x + y) carefully
279         var w = x + y;
280         var z = %_ConstructDouble(%_DoubleHi(w), 0);
281         var v = y - (z - x);
282         var a = -1 / w;
283         var t = %_ConstructDouble(%_DoubleHi(a), 0);
284         var s = 1 + t * z;
285         return t + a * (s + t * v);
286       }
287     }
288   }
289   if (ix >= 0x3fe59428) {  // |x| > .6744
290     if (x < 0) {
291       x = -x;
292       y = -y;
293     }
294     z = PIO4 - x;
295     w = PIO4LO - y;
296     x = z + w;
297     y = 0;
298   }
299   z = x * x;
300   w = z * z;
301
302   // Break x^5 * (T1 + x^2*T2 + ...) into
303   // x^5 * (T1 + x^4*T3 + ... + x^20*T11) +
304   // x^5 * (x^2 * (T2 + x^4*T4 + ... + x^22*T12))
305   var r = KTAN(1) + w * (KTAN(3) + w * (KTAN(5) +
306                     w * (KTAN(7) + w * (KTAN(9) + w * KTAN(11)))));
307   var v = z * (KTAN(2) + w * (KTAN(4) + w * (KTAN(6) +
308                          w * (KTAN(8) + w * (KTAN(10) + w * KTAN(12))))));
309   var s = z * x;
310   r = y + z * (s * (r + v) + y);
311   r = r + KTAN(0) * s;
312   w = x + r;
313   if (ix >= 0x3fe59428) {
314     return (1 - ((hx >> 30) & 2)) *
315       (returnTan - 2.0 * (x - (w * w / (w + returnTan) - r)));
316   }
317   if (returnTan == 1) {
318     return w;
319   } else {
320     z = %_ConstructDouble(%_DoubleHi(w), 0);
321     v = r - (z - x);
322     var a = -1 / w;
323     var t = %_ConstructDouble(%_DoubleHi(a), 0);
324     s = 1 + t * z;
325     return t + a * (s + t * v);
326   }
327 }
328
329 function MathSinSlow(x) {
330   REMPIO2(x);
331   var sign = 1 - (n & 2);
332   if (n & 1) {
333     RETURN_KERNELCOS(y0, y1, * sign);
334   } else {
335     RETURN_KERNELSIN(y0, y1, * sign);
336   }
337 }
338
339 function MathCosSlow(x) {
340   REMPIO2(x);
341   if (n & 1) {
342     var sign = (n & 2) - 1;
343     RETURN_KERNELSIN(y0, y1, * sign);
344   } else {
345     var sign = 1 - (n & 2);
346     RETURN_KERNELCOS(y0, y1, * sign);
347   }
348 }
349
350 // ECMA 262 - 15.8.2.16
351 function MathSin(x) {
352   x = +x;  // Convert to number.
353   if ((%_DoubleHi(x) & 0x7fffffff) <= 0x3fe921fb) {
354     // |x| < pi/4, approximately.  No reduction needed.
355     RETURN_KERNELSIN(x, 0, /* empty */);
356   }
357   return +MathSinSlow(x);
358 }
359
360 // ECMA 262 - 15.8.2.7
361 function MathCos(x) {
362   x = +x;  // Convert to number.
363   if ((%_DoubleHi(x) & 0x7fffffff) <= 0x3fe921fb) {
364     // |x| < pi/4, approximately.  No reduction needed.
365     RETURN_KERNELCOS(x, 0, /* empty */);
366   }
367   return +MathCosSlow(x);
368 }
369
370 // ECMA 262 - 15.8.2.18
371 function MathTan(x) {
372   x = x * 1;  // Convert to number.
373   if ((%_DoubleHi(x) & 0x7fffffff) <= 0x3fe921fb) {
374     // |x| < pi/4, approximately.  No reduction needed.
375     return KernelTan(x, 0, 1);
376   }
377   REMPIO2(x);
378   return KernelTan(y0, y1, (n & 1) ? -1 : 1);
379 }
380
381 // ES6 draft 09-27-13, section 20.2.2.20.
382 // Math.log1p
383 //
384 // Method :                  
385 //   1. Argument Reduction: find k and f such that 
386 //                      1+x = 2^k * (1+f), 
387 //         where  sqrt(2)/2 < 1+f < sqrt(2) .
388 //
389 //      Note. If k=0, then f=x is exact. However, if k!=0, then f
390 //      may not be representable exactly. In that case, a correction
391 //      term is need. Let u=1+x rounded. Let c = (1+x)-u, then
392 //      log(1+x) - log(u) ~ c/u. Thus, we proceed to compute log(u),
393 //      and add back the correction term c/u.
394 //      (Note: when x > 2**53, one can simply return log(x))
395 //
396 //   2. Approximation of log1p(f).
397 //      Let s = f/(2+f) ; based on log(1+f) = log(1+s) - log(1-s)
398 //            = 2s + 2/3 s**3 + 2/5 s**5 + .....,
399 //            = 2s + s*R
400 //      We use a special Reme algorithm on [0,0.1716] to generate 
401 //      a polynomial of degree 14 to approximate R The maximum error 
402 //      of this polynomial approximation is bounded by 2**-58.45. In
403 //      other words,
404 //                      2      4      6      8      10      12      14
405 //          R(z) ~ Lp1*s +Lp2*s +Lp3*s +Lp4*s +Lp5*s  +Lp6*s  +Lp7*s
406 //      (the values of Lp1 to Lp7 are listed in the program)
407 //      and
408 //          |      2          14          |     -58.45
409 //          | Lp1*s +...+Lp7*s    -  R(z) | <= 2 
410 //          |                             |
411 //      Note that 2s = f - s*f = f - hfsq + s*hfsq, where hfsq = f*f/2.
412 //      In order to guarantee error in log below 1ulp, we compute log
413 //      by
414 //              log1p(f) = f - (hfsq - s*(hfsq+R)).
415 //
416 //      3. Finally, log1p(x) = k*ln2 + log1p(f).  
417 //                           = k*ln2_hi+(f-(hfsq-(s*(hfsq+R)+k*ln2_lo)))
418 //         Here ln2 is split into two floating point number: 
419 //                      ln2_hi + ln2_lo,
420 //         where n*ln2_hi is always exact for |n| < 2000.
421 //
422 // Special cases:
423 //      log1p(x) is NaN with signal if x < -1 (including -INF) ; 
424 //      log1p(+INF) is +INF; log1p(-1) is -INF with signal;
425 //      log1p(NaN) is that NaN with no signal.
426 //
427 // Accuracy:
428 //      according to an error analysis, the error is always less than
429 //      1 ulp (unit in the last place).
430 //
431 // Constants:
432 //      Constants are found in fdlibm.cc. We assume the C++ compiler to convert
433 //      from decimal to binary accurately enough to produce the intended values.
434 //
435 // Note: Assuming log() return accurate answer, the following
436 //       algorithm can be used to compute log1p(x) to within a few ULP:
437 //
438 //              u = 1+x;
439 //              if (u==1.0) return x ; else
440 //                          return log(u)*(x/(u-1.0));
441 //
442 //       See HP-15C Advanced Functions Handbook, p.193.
443 //
444 const LN2_HI    = kMath[34];
445 const LN2_LO    = kMath[35];
446 const TWO_THIRD = kMath[36];
447 macro KLOG1P(x)
448 (kMath[37+x])
449 endmacro
450 // 2^54
451 const TWO54 = 18014398509481984;
452
453 function MathLog1p(x) {
454   x = x * 1;  // Convert to number.
455   var hx = %_DoubleHi(x);
456   var ax = hx & 0x7fffffff;
457   var k = 1;
458   var f = x;
459   var hu = 1;
460   var c = 0;
461   var u = x;
462
463   if (hx < 0x3fda827a) {
464     // x < 0.41422
465     if (ax >= 0x3ff00000) {  // |x| >= 1
466       if (x === -1) {
467         return -INFINITY;  // log1p(-1) = -inf
468       } else {
469         return NAN;  // log1p(x<-1) = NaN
470       }
471     } else if (ax < 0x3c900000)  {
472       // For |x| < 2^-54 we can return x.
473       return x;
474     } else if (ax < 0x3e200000) {
475       // For |x| < 2^-29 we can use a simple two-term Taylor series.
476       return x - x * x * 0.5;
477     }
478
479     if ((hx > 0) || (hx <= -0x402D413D)) {  // (int) 0xbfd2bec3 = -0x402d413d
480       // -.2929 < x < 0.41422
481       k = 0;
482     }
483   }
484
485   // Handle Infinity and NAN
486   if (hx >= 0x7ff00000) return x;
487
488   if (k !== 0) {
489     if (hx < 0x43400000) {
490       // x < 2^53
491       u = 1 + x;
492       hu = %_DoubleHi(u);
493       k = (hu >> 20) - 1023;
494       c = (k > 0) ? 1 - (u - x) : x - (u - 1);
495       c = c / u;
496     } else {
497       hu = %_DoubleHi(u);
498       k = (hu >> 20) - 1023;
499     }
500     hu = hu & 0xfffff;
501     if (hu < 0x6a09e) {
502       u = %_ConstructDouble(hu | 0x3ff00000, %_DoubleLo(u));  // Normalize u.
503     } else {
504       ++k;
505       u = %_ConstructDouble(hu | 0x3fe00000, %_DoubleLo(u));  // Normalize u/2.
506       hu = (0x00100000 - hu) >> 2;
507     }
508     f = u - 1;
509   }
510
511   var hfsq = 0.5 * f * f;
512   if (hu === 0) {
513     // |f| < 2^-20;
514     if (f === 0) {
515       if (k === 0) {
516         return 0.0;
517       } else {
518         return k * LN2_HI + (c + k * LN2_LO);
519       }
520     }
521     var R = hfsq * (1 - TWO_THIRD * f);
522     if (k === 0) {
523       return f - R;
524     } else {
525       return k * LN2_HI - ((R - (k * LN2_LO + c)) - f);
526     }
527   }
528
529   var s = f / (2 + f); 
530   var z = s * s;
531   var R = z * (KLOG1P(0) + z * (KLOG1P(1) + z *
532               (KLOG1P(2) + z * (KLOG1P(3) + z *
533               (KLOG1P(4) + z * (KLOG1P(5) + z * KLOG1P(6)))))));
534   if (k === 0) {
535     return f - (hfsq - s * (hfsq + R));
536   } else {
537     return k * LN2_HI - ((hfsq - (s * (hfsq + R) + (k * LN2_LO + c))) - f);
538   }
539 }
540
541 // ES6 draft 09-27-13, section 20.2.2.14.
542 // Math.expm1
543 // Returns exp(x)-1, the exponential of x minus 1.
544 //
545 // Method
546 //   1. Argument reduction:
547 //      Given x, find r and integer k such that
548 //
549 //               x = k*ln2 + r,  |r| <= 0.5*ln2 ~ 0.34658  
550 //
551 //      Here a correction term c will be computed to compensate 
552 //      the error in r when rounded to a floating-point number.
553 //
554 //   2. Approximating expm1(r) by a special rational function on
555 //      the interval [0,0.34658]:
556 //      Since
557 //          r*(exp(r)+1)/(exp(r)-1) = 2+ r^2/6 - r^4/360 + ...
558 //      we define R1(r*r) by
559 //          r*(exp(r)+1)/(exp(r)-1) = 2+ r^2/6 * R1(r*r)
560 //      That is,
561 //          R1(r**2) = 6/r *((exp(r)+1)/(exp(r)-1) - 2/r)
562 //                   = 6/r * ( 1 + 2.0*(1/(exp(r)-1) - 1/r))
563 //                   = 1 - r^2/60 + r^4/2520 - r^6/100800 + ...
564 //      We use a special Remes algorithm on [0,0.347] to generate 
565 //      a polynomial of degree 5 in r*r to approximate R1. The 
566 //      maximum error of this polynomial approximation is bounded 
567 //      by 2**-61. In other words,
568 //          R1(z) ~ 1.0 + Q1*z + Q2*z**2 + Q3*z**3 + Q4*z**4 + Q5*z**5
569 //      where   Q1  =  -1.6666666666666567384E-2,
570 //              Q2  =   3.9682539681370365873E-4,
571 //              Q3  =  -9.9206344733435987357E-6,
572 //              Q4  =   2.5051361420808517002E-7,
573 //              Q5  =  -6.2843505682382617102E-9;
574 //      (where z=r*r, and the values of Q1 to Q5 are listed below)
575 //      with error bounded by
576 //          |                  5           |     -61
577 //          | 1.0+Q1*z+...+Q5*z   -  R1(z) | <= 2 
578 //          |                              |
579 //
580 //      expm1(r) = exp(r)-1 is then computed by the following 
581 //      specific way which minimize the accumulation rounding error: 
582 //                             2     3
583 //                            r     r    [ 3 - (R1 + R1*r/2)  ]
584 //            expm1(r) = r + --- + --- * [--------------------]
585 //                            2     2    [ 6 - r*(3 - R1*r/2) ]
586 //
587 //      To compensate the error in the argument reduction, we use
588 //              expm1(r+c) = expm1(r) + c + expm1(r)*c 
589 //                         ~ expm1(r) + c + r*c 
590 //      Thus c+r*c will be added in as the correction terms for
591 //      expm1(r+c). Now rearrange the term to avoid optimization 
592 //      screw up:
593 //                      (      2                                    2 )
594 //                      ({  ( r    [ R1 -  (3 - R1*r/2) ]  )  }    r  )
595 //       expm1(r+c)~r - ({r*(--- * [--------------------]-c)-c} - --- )
596 //                      ({  ( 2    [ 6 - r*(3 - R1*r/2) ]  )  }    2  )
597 //                      (                                             )
598 //
599 //                 = r - E
600 //   3. Scale back to obtain expm1(x):
601 //      From step 1, we have
602 //         expm1(x) = either 2^k*[expm1(r)+1] - 1
603 //                  = or     2^k*[expm1(r) + (1-2^-k)]
604 //   4. Implementation notes:
605 //      (A). To save one multiplication, we scale the coefficient Qi
606 //           to Qi*2^i, and replace z by (x^2)/2.
607 //      (B). To achieve maximum accuracy, we compute expm1(x) by
608 //        (i)   if x < -56*ln2, return -1.0, (raise inexact if x!=inf)
609 //        (ii)  if k=0, return r-E
610 //        (iii) if k=-1, return 0.5*(r-E)-0.5
611 //        (iv)  if k=1 if r < -0.25, return 2*((r+0.5)- E)
612 //                     else          return  1.0+2.0*(r-E);
613 //        (v)   if (k<-2||k>56) return 2^k(1-(E-r)) - 1 (or exp(x)-1)
614 //        (vi)  if k <= 20, return 2^k((1-2^-k)-(E-r)), else
615 //        (vii) return 2^k(1-((E+2^-k)-r)) 
616 //
617 // Special cases:
618 //      expm1(INF) is INF, expm1(NaN) is NaN;
619 //      expm1(-INF) is -1, and
620 //      for finite argument, only expm1(0)=0 is exact.
621 //
622 // Accuracy:
623 //      according to an error analysis, the error is always less than
624 //      1 ulp (unit in the last place).
625 //
626 // Misc. info.
627 //      For IEEE double 
628 //          if x > 7.09782712893383973096e+02 then expm1(x) overflow
629 //
630 const KEXPM1_OVERFLOW = kMath[44];
631 const INVLN2          = kMath[45];
632 macro KEXPM1(x)
633 (kMath[46+x])
634 endmacro
635
636 function MathExpm1(x) {
637   x = x * 1;  // Convert to number.
638   var y;
639   var hi;
640   var lo;
641   var k;
642   var t;
643   var c;
644     
645   var hx = %_DoubleHi(x);
646   var xsb = hx & 0x80000000;     // Sign bit of x
647   var y = (xsb === 0) ? x : -x;  // y = |x|
648   hx &= 0x7fffffff;              // High word of |x|
649
650   // Filter out huge and non-finite argument
651   if (hx >= 0x4043687a) {     // if |x| ~=> 56 * ln2
652     if (hx >= 0x40862e42) {   // if |x| >= 709.78
653       if (hx >= 0x7ff00000) {
654         // expm1(inf) = inf; expm1(-inf) = -1; expm1(nan) = nan;
655         return (x === -INFINITY) ? -1 : x;
656       }
657       if (x > KEXPM1_OVERFLOW) return INFINITY;  // Overflow
658     }
659     if (xsb != 0) return -1;  // x < -56 * ln2, return -1.
660   }
661
662   // Argument reduction
663   if (hx > 0x3fd62e42) {    // if |x| > 0.5 * ln2
664     if (hx < 0x3ff0a2b2) {  // and |x| < 1.5 * ln2
665       if (xsb === 0) {
666         hi = x - LN2_HI;
667         lo = LN2_LO;
668         k = 1;
669       } else {
670         hi = x + LN2_HI;
671         lo = -LN2_LO;
672         k = -1;
673       }
674     } else {
675       k = (INVLN2 * x + ((xsb === 0) ? 0.5 : -0.5)) | 0;
676       t = k;
677       // t * ln2_hi is exact here.
678       hi = x - t * LN2_HI;
679       lo = t * LN2_LO;
680     }
681     x = hi - lo;
682     c = (hi - x) - lo;
683   } else if (hx < 0x3c900000)   {
684     // When |x| < 2^-54, we can return x.
685     return x;
686   } else {
687     // Fall through.
688     k = 0;
689   }
690
691   // x is now in primary range
692   var hfx = 0.5 * x;
693   var hxs = x * hfx;
694   var r1 = 1 + hxs * (KEXPM1(0) + hxs * (KEXPM1(1) + hxs *
695                      (KEXPM1(2) + hxs * (KEXPM1(3) + hxs * KEXPM1(4)))));
696   t = 3 - r1 * hfx;
697   var e = hxs * ((r1 - t) / (6 - x * t));
698   if (k === 0) {  // c is 0
699     return x - (x*e - hxs);
700   } else {
701     e = (x * (e - c) - c);
702     e -= hxs;
703     if (k === -1) return 0.5 * (x - e) - 0.5;
704     if (k === 1) {
705       if (x < -0.25) return -2 * (e - (x + 0.5));
706       return 1 + 2 * (x - e);
707     }
708
709     if (k <= -2 || k > 56) {
710       // suffice to return exp(x) + 1
711       y = 1 - (e - x);
712       // Add k to y's exponent
713       y = %_ConstructDouble(%_DoubleHi(y) + (k << 20), %_DoubleLo(y));
714       return y - 1;
715     }
716     if (k < 20) {
717       // t = 1 - 2^k
718       t = %_ConstructDouble(0x3ff00000 - (0x200000 >> k), 0);
719       y = t - (e - x);
720       // Add k to y's exponent
721       y = %_ConstructDouble(%_DoubleHi(y) + (k << 20), %_DoubleLo(y));
722     } else {
723       // t = 2^-k
724       t = %_ConstructDouble((0x3ff - k) << 20, 0);
725       y = x - (e + t);
726       y += 1;
727       // Add k to y's exponent
728       y = %_ConstructDouble(%_DoubleHi(y) + (k << 20), %_DoubleLo(y));
729     }
730   }
731   return y;
732 }
733
734
735 // ES6 draft 09-27-13, section 20.2.2.30.
736 // Math.sinh
737 // Method :
738 // mathematically sinh(x) if defined to be (exp(x)-exp(-x))/2
739 //      1. Replace x by |x| (sinh(-x) = -sinh(x)).
740 //      2.
741 //                                                  E + E/(E+1)
742 //          0        <= x <= 22     :  sinh(x) := --------------, E=expm1(x)
743 //                                                      2
744 //
745 //          22       <= x <= lnovft :  sinh(x) := exp(x)/2 
746 //          lnovft   <= x <= ln2ovft:  sinh(x) := exp(x/2)/2 * exp(x/2)
747 //          ln2ovft  <  x           :  sinh(x) := x*shuge (overflow)
748 //
749 // Special cases:
750 //      sinh(x) is |x| if x is +Infinity, -Infinity, or NaN.
751 //      only sinh(0)=0 is exact for finite x.
752 //
753 const KSINH_OVERFLOW = kMath[51];
754 const TWO_M28 = 3.725290298461914e-9;  // 2^-28, empty lower half
755 const LOG_MAXD = 709.7822265625;  // 0x40862e42 00000000, empty lower half
756
757 function MathSinh(x) {
758   x = x * 1;  // Convert to number.
759   var h = (x < 0) ? -0.5 : 0.5;
760   // |x| in [0, 22]. return sign(x)*0.5*(E+E/(E+1))
761   var ax = $abs(x);
762   if (ax < 22) {
763     // For |x| < 2^-28, sinh(x) = x
764     if (ax < TWO_M28) return x;
765     var t = MathExpm1(ax);
766     if (ax < 1) return h * (2 * t - t * t / (t + 1));
767     return h * (t + t / (t + 1));
768   }
769   // |x| in [22, log(maxdouble)], return 0.5 * exp(|x|)
770   if (ax < LOG_MAXD) return h * $exp(ax);
771   // |x| in [log(maxdouble), overflowthreshold]
772   // overflowthreshold = 710.4758600739426
773   if (ax <= KSINH_OVERFLOW) {
774     var w = $exp(0.5 * ax);
775     var t = h * w;
776     return t * w;
777   }
778   // |x| > overflowthreshold or is NaN.
779   // Return Infinity of the appropriate sign or NaN.
780   return x * INFINITY;
781 }
782
783
784 // ES6 draft 09-27-13, section 20.2.2.12.
785 // Math.cosh
786 // Method : 
787 // mathematically cosh(x) if defined to be (exp(x)+exp(-x))/2
788 //      1. Replace x by |x| (cosh(x) = cosh(-x)). 
789 //      2.
790 //                                                      [ exp(x) - 1 ]^2 
791 //          0        <= x <= ln2/2  :  cosh(x) := 1 + -------------------
792 //                                                         2*exp(x)
793 //
794 //                                                 exp(x) + 1/exp(x)
795 //          ln2/2    <= x <= 22     :  cosh(x) := -------------------
796 //                                                        2
797 //          22       <= x <= lnovft :  cosh(x) := exp(x)/2 
798 //          lnovft   <= x <= ln2ovft:  cosh(x) := exp(x/2)/2 * exp(x/2)
799 //          ln2ovft  <  x           :  cosh(x) := huge*huge (overflow)
800 //
801 // Special cases:
802 //      cosh(x) is |x| if x is +INF, -INF, or NaN.
803 //      only cosh(0)=1 is exact for finite x.
804 //
805 const KCOSH_OVERFLOW = kMath[51];
806
807 function MathCosh(x) {
808   x = x * 1;  // Convert to number.
809   var ix = %_DoubleHi(x) & 0x7fffffff;
810   // |x| in [0,0.5*log2], return 1+expm1(|x|)^2/(2*exp(|x|))
811   if (ix < 0x3fd62e43) {
812     var t = MathExpm1($abs(x));
813     var w = 1 + t;
814     // For |x| < 2^-55, cosh(x) = 1
815     if (ix < 0x3c800000) return w;
816     return 1 + (t * t) / (w + w);
817   }
818   // |x| in [0.5*log2, 22], return (exp(|x|)+1/exp(|x|)/2
819   if (ix < 0x40360000) {
820     var t = $exp($abs(x));
821     return 0.5 * t + 0.5 / t;
822   }
823   // |x| in [22, log(maxdouble)], return half*exp(|x|)
824   if (ix < 0x40862e42) return 0.5 * $exp($abs(x));
825   // |x| in [log(maxdouble), overflowthreshold]
826   if ($abs(x) <= KCOSH_OVERFLOW) {
827     var w = $exp(0.5 * $abs(x));
828     var t = 0.5 * w;
829     return t * w;
830   }
831   if (NUMBER_IS_NAN(x)) return x;
832   // |x| > overflowthreshold.
833   return INFINITY;
834 }
835
836 // ES6 draft 09-27-13, section 20.2.2.21.
837 // Return the base 10 logarithm of x
838 //
839 // Method :
840 //      Let log10_2hi = leading 40 bits of log10(2) and
841 //          log10_2lo = log10(2) - log10_2hi,
842 //          ivln10   = 1/log(10) rounded.
843 //      Then
844 //              n = ilogb(x),
845 //              if(n<0)  n = n+1;
846 //              x = scalbn(x,-n);
847 //              log10(x) := n*log10_2hi + (n*log10_2lo + ivln10*log(x))
848 //
849 // Note 1:
850 //      To guarantee log10(10**n)=n, where 10**n is normal, the rounding
851 //      mode must set to Round-to-Nearest.
852 // Note 2:
853 //      [1/log(10)] rounded to 53 bits has error .198 ulps;
854 //      log10 is monotonic at all binary break points.
855 //
856 // Special cases:
857 //      log10(x) is NaN if x < 0;
858 //      log10(+INF) is +INF; log10(0) is -INF;
859 //      log10(NaN) is that NaN;
860 //      log10(10**N) = N  for N=0,1,...,22.
861 //
862
863 const IVLN10 = kMath[52];
864 const LOG10_2HI = kMath[53];
865 const LOG10_2LO = kMath[54];
866
867 function MathLog10(x) {
868   x = x * 1;  // Convert to number.
869   var hx = %_DoubleHi(x);
870   var lx = %_DoubleLo(x);
871   var k = 0;
872
873   if (hx < 0x00100000) {
874     // x < 2^-1022
875     // log10(+/- 0) = -Infinity.
876     if (((hx & 0x7fffffff) | lx) === 0) return -INFINITY;
877     // log10 of negative number is NaN.
878     if (hx < 0) return NAN;
879     // Subnormal number. Scale up x.
880     k -= 54;
881     x *= TWO54;
882     hx = %_DoubleHi(x);
883     lx = %_DoubleLo(x);
884   }
885
886   // Infinity or NaN.
887   if (hx >= 0x7ff00000) return x;
888
889   k += (hx >> 20) - 1023;
890   i = (k & 0x80000000) >> 31;
891   hx = (hx & 0x000fffff) | ((0x3ff - i) << 20);
892   y = k + i;
893   x = %_ConstructDouble(hx, lx);
894
895   z = y * LOG10_2LO + IVLN10 * %_MathLogRT(x);
896   return z + y * LOG10_2HI;
897 }
898
899
900 // ES6 draft 09-27-13, section 20.2.2.22.
901 // Return the base 2 logarithm of x
902 //
903 // fdlibm does not have an explicit log2 function, but fdlibm's pow
904 // function does implement an accurate log2 function as part of the
905 // pow implementation.  This extracts the core parts of that as a
906 // separate log2 function.
907
908 // Method:
909 // Compute log2(x) in two pieces:
910 // log2(x) = w1 + w2
911 // where w1 has 53-24 = 29 bits of trailing zeroes.
912
913 const DP_H = kMath[64];
914 const DP_L = kMath[65];
915
916 // Polynomial coefficients for (3/2)*(log2(x) - 2*s - 2/3*s^3)
917 macro KLOG2(x)
918 (kMath[55+x])
919 endmacro
920
921 // cp = 2/(3*ln(2)). Note that cp_h + cp_l is cp, but with more accuracy.
922 const CP = kMath[61];
923 const CP_H = kMath[62];
924 const CP_L = kMath[63];
925 // 2^53
926 const TWO53 = 9007199254740992; 
927
928 function MathLog2(x) {
929   x = x * 1;  // Convert to number.
930   var ax = $abs(x);
931   var hx = %_DoubleHi(x);
932   var lx = %_DoubleLo(x);
933   var ix = hx & 0x7fffffff;
934
935   // Handle special cases.
936   // log2(+/- 0) = -Infinity
937   if ((ix | lx) == 0) return -INFINITY;
938
939   // log(x) = NaN, if x < 0
940   if (hx < 0) return NAN;
941
942   // log2(Infinity) = Infinity, log2(NaN) = NaN
943   if (ix >= 0x7ff00000) return x;
944
945   var n = 0;
946
947   // Take care of subnormal number.
948   if (ix < 0x00100000) {
949     ax *= TWO53;
950     n -= 53;
951     ix = %_DoubleHi(ax);
952   }
953
954   n += (ix >> 20) - 0x3ff;
955   var j = ix & 0x000fffff;
956
957   // Determine interval.
958   ix = j | 0x3ff00000;  // normalize ix.
959
960   var bp = 1;
961   var dp_h = 0;
962   var dp_l = 0;
963   if (j > 0x3988e) {  // |x| > sqrt(3/2)
964     if (j < 0xbb67a) {  // |x| < sqrt(3)
965       bp = 1.5;
966       dp_h = DP_H;
967       dp_l = DP_L;
968     } else {
969       n += 1;
970       ix -= 0x00100000;
971     }
972   }
973  
974   ax = %_ConstructDouble(ix, %_DoubleLo(ax));
975
976   // Compute ss = s_h + s_l = (x - 1)/(x+1) or (x - 1.5)/(x + 1.5)
977   var u = ax - bp;
978   var v = 1 / (ax + bp);
979   var ss = u * v;
980   var s_h = %_ConstructDouble(%_DoubleHi(ss), 0);
981
982   // t_h = ax + bp[k] High
983   var t_h = %_ConstructDouble(%_DoubleHi(ax + bp), 0)
984   var t_l = ax - (t_h - bp);
985   var s_l = v * ((u - s_h * t_h) - s_h * t_l);
986
987   // Compute log2(ax)
988   var s2 = ss * ss;
989   var r = s2 * s2 * (KLOG2(0) + s2 * (KLOG2(1) + s2 * (KLOG2(2) + s2 * (
990                      KLOG2(3) + s2 * (KLOG2(4) + s2 * KLOG2(5))))));
991   r += s_l * (s_h + ss);
992   s2  = s_h * s_h;
993   t_h = %_ConstructDouble(%_DoubleHi(3.0 + s2 + r), 0);
994   t_l = r - ((t_h - 3.0) - s2);
995   // u + v = ss * (1 + ...)
996   u = s_h * t_h;
997   v = s_l * t_h + t_l * ss;
998
999   // 2 / (3 * log(2)) * (ss + ...)
1000   p_h = %_ConstructDouble(%_DoubleHi(u + v), 0);
1001   p_l = v - (p_h - u);
1002   z_h = CP_H * p_h;
1003   z_l = CP_L * p_h + p_l * CP + dp_l;
1004
1005   // log2(ax) = (ss + ...) * 2 / (3 * log(2)) = n + dp_h + z_h + z_l
1006   var t = n;
1007   var t1 = %_ConstructDouble(%_DoubleHi(((z_h + z_l) + dp_h) + t), 0);
1008   var t2 = z_l - (((t1 - t) - dp_h) - z_h);
1009
1010   // t1 + t2 = log2(ax), sum up because we do not care about extra precision.
1011   return t1 + t2;
1012 }
1013
1014 //-------------------------------------------------------------------
1015
1016 InstallFunctions(GlobalMath, DONT_ENUM, GlobalArray(
1017   "cos", MathCos,
1018   "sin", MathSin,
1019   "tan", MathTan,
1020   "sinh", MathSinh,
1021   "cosh", MathCosh,
1022   "log10", MathLog10,
1023   "log2", MathLog2,
1024   "log1p", MathLog1p,
1025   "expm1", MathExpm1
1026 ));
1027
1028 %SetInlineBuiltinFlag(MathSin);
1029 %SetInlineBuiltinFlag(MathCos);
1030
1031 })();