1 /*
   2  * Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang;
  27 
  28 /**
  29  * Port of the "Freely Distributable Math Library", version 5.3, from C to Java.
  30  *
  31  * <p>The C version of fdlibm relied on the idiom of pointer aliasing
  32  * a 64-bit double floating-point value as a two-element array of
  33  * 32-bit integers and reading and writing the two halves of the
  34  * double independently. This coding pattern was problematic to C
  35  * optimizers and not directly expressible in Java. Therefore, rather
  36  * than a memory level overlay, if portions of a double need to be
  37  * operated on as integer values, the standard library methods for
  38  * bitwise floating-point to integer conversion,
  39  * Double.longBitsToDouble and Double.doubleToRawLongBits, are directly
  40  * or indirectly used .
  41  *
  42  * <p>The C version of fdlibm also took some pains to signal the
  43  * correct IEEE 754 exceptional conditions divide by zero, invalid,
  44  * overflow and underflow. For example, overflow would be signaled by
  45  * {@code huge * huge} where {@code huge} was a large constant that
  46  * would overflow when squared. Since IEEE floating-point exceptional
  47  * handling is not supported natively in the JVM, such coding patterns
  48  * have been omitted from this port. For example, rather than {@code
  49  * return huge * huge}, this port will use {@code return INFINITY}.
  50  */
  51 class FdLibm {
  52     // Constants used by multiple algorithms
  53     private static final double INFINITY = Double.POSITIVE_INFINITY;
  54 
  55     private FdLibm() {
  56         throw new UnsupportedOperationException("No instances for you.");
  57     }
  58 
  59     /**
  60      * Return the low-order 32 bits of the double argument as an int.
  61      */
  62     private static int __LO(double x) {
  63         long transducer = Double.doubleToRawLongBits(x);
  64         return (int)transducer;
  65     }
  66 
  67     /**
  68      * Return a double with its low-order bits of the second argument
  69      * and the high-order bits of the first argument..
  70      */
  71     private static double __LO(double x, int low) {
  72         long transX = Double.doubleToRawLongBits(x);
  73         return Double.longBitsToDouble((transX & 0xFFFF_FFFF_0000_0000L)|low );
  74     }
  75 
  76     /**
  77      * Return the high-order 32 bits of the double argument as an int.
  78      */
  79     private static int __HI(double x) {
  80         long transducer = Double.doubleToRawLongBits(x);
  81         return (int)(transducer >> 32);
  82     }
  83 
  84     /**
  85      * Return a double with its high-order bits of the second argument
  86      * and the low-order bits of the first argument..
  87      */
  88     private static double __HI(double x, int high) {
  89         long transX = Double.doubleToRawLongBits(x);
  90         return Double.longBitsToDouble((transX & 0x0000_0000_FFFF_FFFFL)|( ((long)high)) << 32 );
  91     }
  92 
  93     /** 
  94      * hypot(x,y)
  95      *
  96      * Method :
  97      *      If (assume round-to-nearest) z=x*x+y*y
  98      *      has error less than sqrt(2)/2 ulp, than
  99      *      sqrt(z) has error less than 1 ulp (exercise).
 100      *
 101      *      So, compute sqrt(x*x+y*y) with some care as
 102      *      follows to get the error below 1 ulp:
 103      *
 104      *      Assume x>y>0;
 105      *      (if possible, set rounding to round-to-nearest)
 106      *      1. if x > 2y  use
 107      *              x1*x1+(y*y+(x2*(x+x1))) for x*x+y*y
 108      *      where x1 = x with lower 32 bits cleared, x2 = x-x1; else
 109      *      2. if x <= 2y use
 110      *              t1*y1+((x-y)*(x-y)+(t1*y2+t2*y))
 111      *      where t1 = 2x with lower 32 bits cleared, t2 = 2x-t1,
 112      *      y1= y with lower 32 bits chopped, y2 = y-y1.
 113      *
 114      *      NOTE: scaling may be necessary if some argument is too
 115      *            large or too tiny
 116      *
 117      * Special cases:
 118      *      hypot(x,y) is INF if x or y is +INF or -INF; else
 119      *      hypot(x,y) is NAN if x or y is NAN.
 120      *
 121      * Accuracy:
 122      *      hypot(x,y) returns sqrt(x^2+y^2) with error less
 123      *      than 1 ulps (units in the last place)
 124      */
 125     public static class Hypot {
 126         public static double compute(double x, double y) {
 127             double a=x,b=y,t1,t2,y1,y2,w;
 128             int j,k,ha,hb;
 129 
 130             ha = __HI(x)&0x7fffffff;        /* high word of  x */
 131             hb = __HI(y)&0x7fffffff;        /* high word of  y */
 132             if(hb > ha) {a=y;b=x;j=ha; ha=hb;hb=j;} else {a=x;b=y;}
 133             a = __HI(a, ha);   /* a <- |a| */
 134             b = __HI(b, hb);   /* b <- |b| */
 135             if((ha-hb)>0x3c00000) {return a+b;} /* x/y > 2**60 */
 136             k=0;
 137             if(ha > 0x5f300000) {   /* a>2**500 */
 138                 if(ha >= 0x7ff00000) {       /* Inf or NaN */
 139                     w = a+b;                 /* for sNaN */
 140                     if(((ha&0xfffff)|__LO(a))==0) w = a;
 141                     if(((hb^0x7ff00000)|__LO(b))==0) w = b;
 142                     return w;
 143                 }
 144                 /* scale a and b by 2**-600 */
 145                 ha -= 0x25800000; hb -= 0x25800000;  k += 600;
 146                 a = __HI(a, ha);
 147                 b = __HI(b, hb);
 148             }
 149             if(hb < 0x20b00000) {   /* b < 2**-500 */
 150                 if(hb <= 0x000fffff) {      /* subnormal b or 0 */
 151                     if((hb|(__LO(b)))==0) return a;
 152                     t1=0;
 153                     t1 = __HI(t1, 0x7fd00000);  /* t1=2^1022 */
 154                     b *= t1;
 155                     a *= t1;
 156                     k -= 1022;
 157                 } else {            /* scale a and b by 2^600 */
 158                     ha += 0x25800000;       /* a *= 2^600 */
 159                     hb += 0x25800000;       /* b *= 2^600 */
 160                     k -= 600;
 161                     a = __HI(a, ha);
 162                     b = __HI(b, hb);
 163                 }
 164             }
 165             /* medium size a and b */
 166             w = a-b;
 167             if (w>b) {
 168                 t1 = 0;
 169                 t1 = __HI(t1, ha);
 170                 t2 = a-t1;
 171                 w  = Math.sqrt(t1*t1-(b*(-b)-t2*(a+t1)));
 172             } else {
 173                 a  = a+a;
 174                 y1 = 0;
 175                 y1 = __HI(y1, hb);
 176                 y2 = b - y1;
 177                 t1 = 0;
 178                 t1 = __HI(t1, ha+0x00100000);
 179                 t2 = a - t1;
 180                 w  = Math.sqrt(t1*y1-(w*(-w)-(t1*y2+t2*b)));
 181             }
 182             if(k!=0) {
 183                 t1 = 1.0;
 184                 int t1_hi = __HI(t1);
 185                 t1_hi += (k<<20);
 186                 t1 = __HI(t1, t1_hi);
 187                 return t1*w;
 188             } else return w;
 189         }
 190     }
 191 
 192     /**
 193      * Compute x**y
 194      *                    n
 195      * Method:  Let x =  2   * (1+f)
 196      *      1. Compute and return log2(x) in two pieces:
 197      *              log2(x) = w1 + w2,
 198      *         where w1 has 53 - 24 = 29 bit trailing zeros.
 199      *      2. Perform y*log2(x) = n+y' by simulating muti-precision
 200      *         arithmetic, where |y'| <= 0.5.
 201      *      3. Return x**y = 2**n*exp(y'*log2)
 202      *
 203      * Special cases:
 204      *      1.  (anything) ** 0  is 1
 205      *      2.  (anything) ** 1  is itself
 206      *      3.  (anything) ** NAN is NAN
 207      *      4.  NAN ** (anything except 0) is NAN
 208      *      5.  +-(|x| > 1) **  +INF is +INF
 209      *      6.  +-(|x| > 1) **  -INF is +0
 210      *      7.  +-(|x| < 1) **  +INF is +0
 211      *      8.  +-(|x| < 1) **  -INF is +INF
 212      *      9.  +-1         ** +-INF is NAN
 213      *      10. +0 ** (+anything except 0, NAN)               is +0
 214      *      11. -0 ** (+anything except 0, NAN, odd integer)  is +0
 215      *      12. +0 ** (-anything except 0, NAN)               is +INF
 216      *      13. -0 ** (-anything except 0, NAN, odd integer)  is +INF
 217      *      14. -0 ** (odd integer) = -( +0 ** (odd integer) )
 218      *      15. +INF ** (+anything except 0,NAN) is +INF
 219      *      16. +INF ** (-anything except 0,NAN) is +0
 220      *      17. -INF ** (anything)  = -0 ** (-anything)
 221      *      18. (-anything) ** (integer) is (-1)**(integer)*(+anything**integer)
 222      *      19. (-anything except 0 and inf) ** (non-integer) is NAN
 223      *
 224      * Accuracy:
 225      *      pow(x,y) returns x**y nearly rounded. In particular
 226      *                      pow(integer,integer)
 227      *      always returns the correct integer provided it is
 228      *      representable.
 229      */
 230     public static class Pow {
 231         public static strictfp double compute(final double x, final double y) {
 232             double z;
 233             double r, s, t, u, v, w;
 234             int i, j, k, n;
 235 
 236             // y == zero: x**0 = 1
 237             if (y == 0.0)
 238                 return 1.0;
 239 
 240             // +/-NaN return x + y to propagate NaN significands
 241             if (Double.isNaN(x) || Double.isNaN(y))
 242                 return x + y;
 243 
 244             final double y_abs = Math.abs(y);
 245             double x_abs   = Math.abs(x);
 246             // Special values of y
 247             if (y == 2.0) {
 248                 return x * x;
 249             } else if (y == 0.5) {
 250                 if (x >= -Double.MAX_VALUE) // Handle x == -infinity later
 251                     return Math.sqrt(x + 0.0); // Add 0.0 to properly handle x == -0.0
 252             } else if (y_abs == 1.0) {        // y is  +/-1
 253                 return (y == 1.0) ? x : 1.0 / x;
 254             } else if (y_abs == INFINITY) {       // y is +/-infinity
 255                 if (x_abs == 1.0)
 256                     return  y - y;         // inf**+/-1 is NaN
 257                 else if (x_abs > 1.0) // (|x| > 1)**+/-inf = inf, 0
 258                     return (y >= 0) ? y : 0.0;
 259                 else                       // (|x| < 1)**-/+inf = inf, 0
 260                     return (y < 0) ? -y : 0.0;
 261             }
 262 
 263             final int hx = __HI(x);
 264             int ix = hx & 0x7fffffff;
 265 
 266             /*
 267              * When x < 0, determine if y is an odd integer:
 268              * y_is_int = 0       ... y is not an integer
 269              * y_is_int = 1       ... y is an odd int
 270              * y_is_int = 2       ... y is an even int
 271              */
 272             int y_is_int  = 0;
 273             if (hx < 0) {
 274                 if (y_abs >= 0x1.0p53)   // |y| >= 2^53 = 9.007199254740992E15
 275                     y_is_int = 2; // y is an even integer since ulp(2^53) = 2.0
 276                 else if (y_abs >= 1.0) { // |y| >= 1.0
 277                     long y_abs_as_long = (long) y_abs;
 278                     if ( ((double) y_abs_as_long) == y_abs) {
 279                         y_is_int = 2 -  (int)(y_abs_as_long & 0x1L);
 280                     }
 281                 }
 282             }
 283 
 284             // Special value of x
 285             if (x_abs == 0.0 ||
 286                 x_abs == INFINITY ||
 287                 x_abs == 1.0) {
 288                 z = x_abs;                 // x is +/-0, +/-inf, +/-1
 289                 if (y < 0.0)
 290                     z = 1.0/z;     // z = (1/|x|)
 291                 if (hx < 0) {
 292                     if (((ix - 0x3ff00000) | y_is_int) == 0) {
 293                         z = (z-z)/(z-z); // (-1)**non-int is NaN
 294                     } else if (y_is_int == 1)
 295                         z = -1.0 * z;             // (x < 0)**odd = -(|x|**odd)
 296                 }
 297                 return z;
 298             }
 299 
 300             n = (hx >> 31) + 1;
 301 
 302             // (x < 0)**(non-int) is NaN
 303             if ((n | y_is_int) == 0)
 304                 return (x-x)/(x-x);
 305 
 306             s = 1.0; // s (sign of result -ve**odd) = -1 else = 1
 307             if ( (n | (y_is_int - 1)) == 0)
 308                 s = -1.0; // (-ve)**(odd int)
 309 
 310             double p_h, p_l, t1, t2;
 311             // |y| is huge
 312             if (y_abs > 0x1.0p31) { // if |y| > 2**31
 313                 final double INV_LN2   =  0x1.7154_7652_b82fep0;   //  1.44269504088896338700e+00 = 1/ln2
 314                 final double INV_LN2_H =  0x1.715476p0;            //  1.44269502162933349609e+00 = 24 bits of 1/ln2
 315                 final double INV_LN2_L =  0x1.4ae0_bf85_ddf44p-26; //  1.92596299112661746887e-08 = 1/ln2 tail
 316 
 317                 // Over/underflow if x is not close to one
 318                 if (x_abs < 0x1.fffffp-1) // |x| < 0.9999995231628418
 319                     return (y < 0.0) ? s * INFINITY : s * 0.0;
 320                 if (x_abs > 1.0)         // |x| > 1.0
 321                     return (y > 0.0) ? s * INFINITY : s * 0.0;
 322                 /*
 323                  * now |1-x| is tiny <= 2**-20, sufficient to compute
 324                  * log(x) by x - x^2/2 + x^3/3 - x^4/4
 325                  */
 326                 t = x_abs - 1.0;        // t has 20 trailing zeros
 327                 w = (t * t) * (0.5 - t * (0.3333333333333333333333 - t * 0.25));
 328                 u = INV_LN2_H * t;      // INV_LN2_H has 21 sig. bits
 329                 v =  t * INV_LN2_L - w * INV_LN2;
 330                 t1 = u + v;
 331                 t1 =__LO(t1, 0);
 332                 t2 = v - (t1 - u);
 333             } else {
 334                 final double CP      =  0x1.ec70_9dc3_a03fdp-1;  //  9.61796693925975554329e-01 = 2/(3ln2)
 335                 final double CP_H    =  0x1.ec709ep-1;           //  9.61796700954437255859e-01 = (float)cp
 336                 final double CP_L    = -0x1.e2fe_0145_b01f5p-28; // -7.02846165095275826516e-09 = tail of CP_H
 337 
 338                 double z_h, z_l, ss, s2, s_h, s_l, t_h, t_l;
 339                 n = 0;
 340                 // Take care of subnormal numbers
 341                 if (ix < 0x00100000) {
 342                     x_abs *= 0x1.0p53; // 2^53 = 9007199254740992.0
 343                     n -= 53;
 344                     ix = __HI(x_abs);
 345                 }
 346                 n  += ((ix) >> 20) - 0x3ff;
 347                 j  = ix & 0x000fffff;
 348                 // Determine interval
 349                 ix = j | 0x3ff00000;          // Normalize ix
 350                 if (j <= 0x3988E)
 351                     k = 0;         // |x| <sqrt(3/2)
 352                 else if (j < 0xBB67A)
 353                     k = 1;         // |x| <sqrt(3)
 354                 else {
 355                     k = 0;
 356                     n += 1;
 357                     ix -= 0x00100000;
 358                 }
 359                 x_abs = __HI(x_abs, ix);
 360 
 361                 // Compute ss = s_h + s_l = (x-1)/(x+1) or (x-1.5)/(x+1.5)
 362 
 363                 final double BP[]    = {1.0,
 364                                        1.5};
 365                 final double DP_H[]  = {0.0,
 366                                         0x1.2b80_34p-1};        // 5.84962487220764160156e-01
 367                 final double DP_L[]  = {0.0,
 368                                         0x1.cfde_b43c_fd006p-27};// 1.35003920212974897128e-08
 369 
 370                 // Poly coefs for (3/2)*(log(x)-2s-2/3*s**3
 371                 final double L1      =  0x1.3333_3333_33303p-1;  //  5.99999999999994648725e-01
 372                 final double L2      =  0x1.b6db_6db6_fabffp-2;  //  4.28571428578550184252e-01
 373                 final double L3      =  0x1.5555_5518_f264dp-2;  //  3.33333329818377432918e-01
 374                 final double L4      =  0x1.1746_0a91_d4101p-2;  //  2.72728123808534006489e-01
 375                 final double L5      =  0x1.d864_a93c_9db65p-3;  //  2.30660745775561754067e-01
 376                 final double L6      =  0x1.a7e2_84a4_54eefp-3;  //  2.06975017800338417784e-01
 377                 u = x_abs - BP[k];               // BP[0]=1.0, BP[1]=1.5
 378                 v = 1.0 / (x_abs + BP[k]);
 379                 ss = u * v;
 380                 s_h = ss;
 381                 s_h = __LO(s_h, 0);
 382                 // t_h=x_abs + BP[k] High
 383                 t_h = 0.0;
 384                 t_h = __HI(t_h, ((ix >> 1) | 0x20000000) + 0x00080000 + (k << 18) );
 385                 t_l = x_abs - (t_h - BP[k]);
 386                 s_l = v * ((u - s_h * t_h) - s_h * t_l);
 387                 // Compute log(x_abs)
 388                 s2 = ss * ss;
 389                 r = s2 * s2* (L1 + s2 * (L2 + s2 * (L3 + s2 * (L4 + s2 * (L5 + s2 * L6)))));
 390                 r += s_l * (s_h + ss);
 391                 s2  = s_h * s_h;
 392                 t_h = 3.0 + s2 + r;
 393                 t_h = __LO(t_h, 0);
 394                 t_l = r - ((t_h - 3.0) - s2);
 395                 // u+v = ss*(1+...)
 396                 u = s_h * t_h;
 397                 v = s_l * t_h + t_l * ss;
 398                 // 2/(3log2)*(ss + ...)
 399                 p_h = u + v;
 400                 p_h = __LO(p_h, 0);
 401                 p_l = v - (p_h - u);
 402                 z_h = CP_H * p_h;             // CP_H + CP_L = 2/(3*log2)
 403                 z_l = CP_L * p_h + p_l * CP + DP_L[k];
 404                 // log2(x_abs) = (ss + ..)*2/(3*log2) = n + DP_H + z_h + z_l
 405                 t = (double)n;
 406                 t1 = (((z_h + z_l) + DP_H[k]) + t);
 407                 t1 = __LO(t1, 0);
 408                 t2 = z_l - (((t1 - t) - DP_H[k]) - z_h);
 409             }
 410 
 411             // Split up y into (y1 + y2) and compute (y1 + y2) * (t1 + t2)
 412             double y1  = y;
 413             y1 = __LO(y1, 0);
 414             p_l = (y - y1) * t1 + y * t2;
 415             p_h = y1 * t1;
 416             z = p_l + p_h;
 417             j = __HI(z);
 418             i = __LO(z);
 419             if (j >= 0x40900000) {                           // z >= 1024
 420                 if (((j - 0x40900000) | i)!=0)               // if z > 1024
 421                     return s * INFINITY;                     // Overflow
 422                 else {
 423                     final double OVT     =  8.0085662595372944372e-0017; // -(1024-log2(ovfl+.5ulp))
 424                     if (p_l + OVT > z - p_h)
 425                         return s * INFINITY;   // Overflow
 426                 }
 427             } else if ((j & 0x7fffffff) >= 0x4090cc00 ) {        // z <= -1075
 428                 if (((j - 0xc090cc00) | i)!=0)           // z < -1075
 429                     return s * 0.0;           // Underflow
 430                 else {
 431                     if (p_l <= z - p_h)
 432                         return s * 0.0;      // Underflow
 433                 }
 434             }
 435             /*
 436              * Compute 2**(p_h+p_l)
 437              */
 438             // Poly coefs for (3/2)*(log(x)-2s-2/3*s**3
 439             final double P1      =  0x1.5555_5555_5553ep-3;  //  1.66666666666666019037e-01
 440             final double P2      = -0x1.6c16_c16b_ebd93p-9;  // -2.77777777770155933842e-03
 441             final double P3      =  0x1.1566_aaf2_5de2cp-14; //  6.61375632143793436117e-05
 442             final double P4      = -0x1.bbd4_1c5d_26bf1p-20; // -1.65339022054652515390e-06
 443             final double P5      =  0x1.6376_972b_ea4d0p-25; //  4.13813679705723846039e-08
 444             final double LG2     =  0x1.62e4_2fef_a39efp-1;  //  6.93147180559945286227e-01
 445             final double LG2_H   =  0x1.62e43p-1;            //  6.93147182464599609375e-01
 446             final double LG2_L   = -0x1.05c6_10ca_86c39p-29; // -1.90465429995776804525e-09
 447             i = j & 0x7fffffff;
 448             k = (i >> 20) - 0x3ff;
 449             n = 0;
 450             if (i > 0x3fe00000) {              // if |z| > 0.5, set n = [z + 0.5]
 451                 n = j + (0x00100000 >> (k + 1));
 452                 k = ((n & 0x7fffffff) >> 20) - 0x3ff;     // new k for n
 453                 t = 0.0;
 454                 t = __HI(t, (n & ~(0x000fffff >> k)) );
 455                 n = ((n & 0x000fffff) | 0x00100000) >> (20 - k);
 456                 if (j < 0)
 457                     n = -n;
 458                 p_h -= t;
 459             }
 460             t = p_l + p_h;
 461             t = __LO(t, 0);
 462             u = t * LG2_H;
 463             v = (p_l - (t - p_h)) * LG2 + t * LG2_L;
 464             z = u + v;
 465             w = v - (z - u);
 466             t  = z * z;
 467             t1  = z - t * (P1 + t * (P2 + t * (P3 + t * (P4 + t * P5))));
 468             r  = (z * t1)/(t1 - 2.0) - (w + z * w);
 469             z  = 1.0 - (r - z);
 470             j  = __HI(z);
 471             j += (n << 20);
 472             if ((j >> 20) <= 0)
 473                 z = Math.scalb(z, n); // subnormal output
 474             else {
 475                 int z_hi = __HI(z);
 476                 z_hi += (n << 20);
 477                 z = __HI(z, z_hi);
 478             }
 479             return s * z;
 480         }
 481     }
 482 }