AccurateMath.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.math4.core.jdkmath;

  18. import java.io.PrintStream;

  19. import org.apache.commons.numbers.core.Precision;

  20. /**
  21.  * Portable alternative to {@link Math} and {@link StrictMath}.
  22.  * <p>
  23.  * Caveat: At the time of implementation, the {@code AccurateMath} functions
  24.  * were often faster and/or more accurate than their JDK equivalent.
  25.  * Nowadays, it would not be surprising that they are always slower (due
  26.  * to the various JVM optimizations that have appeared since Java 5).
  27.  * However, any change to this class should ensure that the current
  28.  * accuracy is not lost.
  29.  * </p>
  30.  * <p>
  31.  * AccurateMath speed is achieved by relying heavily on optimizing compilers
  32.  * to native code present in many JVMs today and use of large tables.
  33.  * The larger tables are lazily initialized on first use, so that the setup
  34.  * time does not penalize methods that don't need them.
  35.  * </p>
  36.  * <p>
  37.  * Note that AccurateMath is extensively used inside Apache Commons Math,
  38.  * so by calling some algorithms, the overhead when the tables need to be
  39.  * initialized will occur regardless of the end-user calling AccurateMath
  40.  * methods directly or not.
  41.  * Performance figures for a specific JVM and hardware can be evaluated by
  42.  * running the AccurateMathTestPerformance tests in the test directory of
  43.  * the source distribution.
  44.  * </p>
  45.  * <p>
  46.  * AccurateMath accuracy should be mostly independent of the JVM as it relies only
  47.  * on IEEE-754 basic operations and on embedded tables. Almost all operations
  48.  * are accurate to about 0.5 ulp throughout the domain range. This statement,
  49.  * of course is only a rough global observed behavior, it is <em>not</em> a
  50.  * guarantee for <em>every</em> double numbers input (see William Kahan's
  51.  * <a href="http://en.wikipedia.org/wiki/Rounding#The_table-maker.27s_dilemma">
  52.  * Table Maker's Dilemma</a>).
  53.  * </p>
  54.  * <p>
  55.  * AccurateMath implements the following methods not found in Math/StrictMath:
  56.  * <ul>
  57.  * <li>{@link #asinh(double)}</li>
  58.  * <li>{@link #acosh(double)}</li>
  59.  * <li>{@link #atanh(double)}</li>
  60.  * </ul>
  61.  *
  62.  * @since 2.2
  63.  */
  64. public final class AccurateMath {
  65.     /** Archimede's constant PI, ratio of circle circumference to diameter. */
  66.     public static final double PI = 105414357.0 / 33554432.0 + 1.984187159361080883e-9;

  67.     /** Napier's constant e, base of the natural logarithm. */
  68.     public static final double E = 2850325.0 / 1048576.0 + 8.254840070411028747e-8;

  69.     /** Index of exp(0) in the array of integer exponentials. */
  70.     static final int EXP_INT_TABLE_MAX_INDEX = 750;
  71.     /** Length of the array of integer exponentials. */
  72.     static final int EXP_INT_TABLE_LEN = EXP_INT_TABLE_MAX_INDEX * 2;
  73.     /** Logarithm table length. */
  74.     static final int LN_MANT_LEN = 1024;
  75.     /** Exponential fractions table length. */
  76.     static final int EXP_FRAC_TABLE_LEN = 1025; // 0, 1/1024, ... 1024/1024

  77.     /** Error message. */
  78.     private static final String ZERO_DENOMINATOR_MSG = "Division by zero";
  79.     /** Error message. */
  80.     private static final String OVERFLOW_MSG = "Overflow";
  81.     /** StrictMath.log(Double.MAX_VALUE): {@value}. */
  82.     private static final double LOG_MAX_VALUE = StrictMath.log(Double.MAX_VALUE);

  83.     /** Indicator for tables initialization.
  84.      * <p>
  85.      * This compile-time constant should be set to true only if one explicitly
  86.      * wants to compute the tables at class loading time instead of using the
  87.      * already computed ones provided as literal arrays below.
  88.      * </p>
  89.      */
  90.     private static final boolean RECOMPUTE_TABLES_AT_RUNTIME = false;

  91.     /** log(2) (high bits). */
  92.     private static final double LN_2_A = 0.693147063255310059;

  93.     /** log(2) (low bits). */
  94.     private static final double LN_2_B = 1.17304635250823482e-7;

  95.     /** Coefficients for log, when input 0.99 < x < 1.01. */
  96.     private static final double[][] LN_QUICK_COEF = {
  97.         {1.0, 5.669184079525E-24},
  98.         {-0.25, -0.25},
  99.         {0.3333333134651184, 1.986821492305628E-8},
  100.         {-0.25, -6.663542893624021E-14},
  101.         {0.19999998807907104, 1.1921056801463227E-8},
  102.         {-0.1666666567325592, -7.800414592973399E-9},
  103.         {0.1428571343421936, 5.650007086920087E-9},
  104.         {-0.12502530217170715, -7.44321345601866E-11},
  105.         {0.11113807559013367, 9.219544613762692E-9},
  106.     };

  107.     /** Coefficients for log in the range of 1.0 < x < 1.0 + 2^-10. */
  108.     private static final double[][] LN_HI_PREC_COEF = {
  109.         {1.0, -6.032174644509064E-23},
  110.         {-0.25, -0.25},
  111.         {0.3333333134651184, 1.9868161777724352E-8},
  112.         {-0.2499999701976776, -2.957007209750105E-8},
  113.         {0.19999954104423523, 1.5830993332061267E-10},
  114.         {-0.16624879837036133, -2.6033824355191673E-8}
  115.     };

  116.     /** Sine, Cosine, Tangent tables are for 0, 1/8, 2/8, ... 13/8 = PI/2 approx. */
  117.     private static final int SINE_TABLE_LEN = 14;

  118.     /** Sine table (high bits). */
  119.     private static final double[] SINE_TABLE_A =
  120.         {
  121.         +0.0d,
  122.         +0.1246747374534607d,
  123.         +0.24740394949913025d,
  124.         +0.366272509098053d,
  125.         +0.4794255495071411d,
  126.         +0.5850973129272461d,
  127.         +0.6816387176513672d,
  128.         +0.7675435543060303d,
  129.         +0.8414709568023682d,
  130.         +0.902267575263977d,
  131.         +0.9489846229553223d,
  132.         +0.9808930158615112d,
  133.         +0.9974949359893799d,
  134.         +0.9985313415527344d,
  135.     };

  136.     /** Sine table (low bits). */
  137.     private static final double[] SINE_TABLE_B =
  138.         {
  139.         +0.0d,
  140.         -4.068233003401932E-9d,
  141.         +9.755392680573412E-9d,
  142.         +1.9987994582857286E-8d,
  143.         -1.0902938113007961E-8d,
  144.         -3.9986783938944604E-8d,
  145.         +4.23719669792332E-8d,
  146.         -5.207000323380292E-8d,
  147.         +2.800552834259E-8d,
  148.         +1.883511811213715E-8d,
  149.         -3.5997360512765566E-9d,
  150.         +4.116164446561962E-8d,
  151.         +5.0614674548127384E-8d,
  152.         -1.0129027912496858E-9d,
  153.     };

  154.     /** Cosine table (high bits). */
  155.     private static final double[] COSINE_TABLE_A =
  156.         {
  157.         +1.0d,
  158.         +0.9921976327896118d,
  159.         +0.9689123630523682d,
  160.         +0.9305076599121094d,
  161.         +0.8775825500488281d,
  162.         +0.8109631538391113d,
  163.         +0.7316888570785522d,
  164.         +0.6409968137741089d,
  165.         +0.5403022766113281d,
  166.         +0.4311765432357788d,
  167.         +0.3153223395347595d,
  168.         +0.19454771280288696d,
  169.         +0.07073719799518585d,
  170.         -0.05417713522911072d,
  171.     };

  172.     /** Cosine table (low bits). */
  173.     private static final double[] COSINE_TABLE_B =
  174.         {
  175.         +0.0d,
  176.         +3.4439717236742845E-8d,
  177.         +5.865827662008209E-8d,
  178.         -3.7999795083850525E-8d,
  179.         +1.184154459111628E-8d,
  180.         -3.43338934259355E-8d,
  181.         +1.1795268640216787E-8d,
  182.         +4.438921624363781E-8d,
  183.         +2.925681159240093E-8d,
  184.         -2.6437112632041807E-8d,
  185.         +2.2860509143963117E-8d,
  186.         -4.813899778443457E-9d,
  187.         +3.6725170580355583E-9d,
  188.         +2.0217439756338078E-10d,
  189.     };


  190.     /** Tangent table, used by atan() (high bits). */
  191.     private static final double[] TANGENT_TABLE_A =
  192.         {
  193.         +0.0d,
  194.         +0.1256551444530487d,
  195.         +0.25534194707870483d,
  196.         +0.3936265707015991d,
  197.         +0.5463024377822876d,
  198.         +0.7214844226837158d,
  199.         +0.9315965175628662d,
  200.         +1.1974215507507324d,
  201.         +1.5574076175689697d,
  202.         +2.092571258544922d,
  203.         +3.0095696449279785d,
  204.         +5.041914939880371d,
  205.         +14.101419448852539d,
  206.         -18.430862426757812d,
  207.     };

  208.     /** Tangent table, used by atan() (low bits). */
  209.     private static final double[] TANGENT_TABLE_B =
  210.         {
  211.         +0.0d,
  212.         -7.877917738262007E-9d,
  213.         -2.5857668567479893E-8d,
  214.         +5.2240336371356666E-9d,
  215.         +5.206150291559893E-8d,
  216.         +1.8307188599677033E-8d,
  217.         -5.7618793749770706E-8d,
  218.         +7.848361555046424E-8d,
  219.         +1.0708593250394448E-7d,
  220.         +1.7827257129423813E-8d,
  221.         +2.893485277253286E-8d,
  222.         +3.1660099222737955E-7d,
  223.         +4.983191803254889E-7d,
  224.         -3.356118100840571E-7d,
  225.     };

  226.     /** Bits of 1/(2*pi), need for reducePayneHanek(). */
  227.     private static final long[] RECIP_2PI = new long[] {
  228.         (0x28be60dbL << 32) | 0x9391054aL,
  229.         (0x7f09d5f4L << 32) | 0x7d4d3770L,
  230.         (0x36d8a566L << 32) | 0x4f10e410L,
  231.         (0x7f9458eaL << 32) | 0xf7aef158L,
  232.         (0x6dc91b8eL << 32) | 0x909374b8L,
  233.         (0x01924bbaL << 32) | 0x82746487L,
  234.         (0x3f877ac7L << 32) | 0x2c4a69cfL,
  235.         (0xba208d7dL << 32) | 0x4baed121L,
  236.         (0x3a671c09L << 32) | 0xad17df90L,
  237.         (0x4e64758eL << 32) | 0x60d4ce7dL,
  238.         (0x272117e2L << 32) | 0xef7e4a0eL,
  239.         (0xc7fe25ffL << 32) | 0xf7816603L,
  240.         (0xfbcbc462L << 32) | 0xd6829b47L,
  241.         (0xdb4d9fb3L << 32) | 0xc9f2c26dL,
  242.         (0xd3d18fd9L << 32) | 0xa797fa8bL,
  243.         (0x5d49eeb1L << 32) | 0xfaf97c5eL,
  244.         (0xcf41ce7dL << 32) | 0xe294a4baL,
  245.         (0x9afed7ecL << 32)};

  246.     /** Bits of pi/4, need for reducePayneHanek(). */
  247.     private static final long[] PI_O_4_BITS = new long[] {
  248.         (0xc90fdaa2L << 32) | 0x2168c234L,
  249.         (0xc4c6628bL << 32) | 0x80dc1cd1L };

  250.     /** Eighths.
  251.      * This is used by sinQ, because its faster to do a table lookup than
  252.      * a multiply in this time-critical routine
  253.      */
  254.     private static final double[] EIGHTHS = {
  255.         0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0, 1.125, 1.25, 1.375, 1.5, 1.625};

  256.     /** Table of 2^((n+2)/3). */
  257.     private static final double[] CBRTTWO = {0.6299605249474366,
  258.                                              0.7937005259840998,
  259.                                              1.0,
  260.                                              1.2599210498948732,
  261.                                              1.5874010519681994};

  262.     /*
  263.      *  There are 52 bits in the mantissa of a double.
  264.      *  For additional precision, the code splits double numbers into two parts,
  265.      *  by clearing the low order 30 bits if possible, and then performs the arithmetic
  266.      *  on each half separately.
  267.      */

  268.     /**
  269.      * 0x40000000 - used to split a double into two parts, both with the low order bits cleared.
  270.      * Equivalent to 2^30.
  271.      */
  272.     private static final long HEX_40000000 = 0x40000000L; // 1073741824L

  273.     /** Mask used to clear low order 30 bits. */
  274.     private static final long MASK_30BITS = -1L - (HEX_40000000 - 1); // 0xFFFFFFFFC0000000L;

  275.     /** Mask used to clear the non-sign part of an int. */
  276.     private static final int MASK_NON_SIGN_INT = 0x7fffffff;

  277.     /** Mask used to clear the non-sign part of a long. */
  278.     private static final long MASK_NON_SIGN_LONG = 0x7fffffffffffffffL;

  279.     /** Mask used to extract exponent from double bits. */
  280.     private static final long MASK_DOUBLE_EXPONENT = 0x7ff0000000000000L;

  281.     /** Mask used to extract mantissa from double bits. */
  282.     private static final long MASK_DOUBLE_MANTISSA = 0x000fffffffffffffL;

  283.     /** Mask used to add implicit high order bit for normalized double. */
  284.     private static final long IMPLICIT_HIGH_BIT = 0x0010000000000000L;

  285.     /** 2^52 - double numbers this large must be integral (no fraction) or NaN or Infinite. */
  286.     private static final double TWO_POWER_52 = 4503599627370496.0;

  287.     /** Constant: {@value}. */
  288.     private static final double F_1_3 = 1d / 3d;
  289.     /** Constant: {@value}. */
  290.     private static final double F_1_5 = 1d / 5d;
  291.     /** Constant: {@value}. */
  292.     private static final double F_1_7 = 1d / 7d;
  293.     /** Constant: {@value}. */
  294.     private static final double F_1_9 = 1d / 9d;
  295.     /** Constant: {@value}. */
  296.     private static final double F_1_11 = 1d / 11d;
  297.     /** Constant: {@value}. */
  298.     private static final double F_1_13 = 1d / 13d;
  299.     /** Constant: {@value}. */
  300.     private static final double F_1_15 = 1d / 15d;
  301.     /** Constant: {@value}. */
  302.     private static final double F_1_17 = 1d / 17d;
  303.     /** Constant: {@value}. */
  304.     private static final double F_3_4 = 3d / 4d;
  305.     /** Constant: {@value}. */
  306.     private static final double F_15_16 = 15d / 16d;
  307.     /** Constant: {@value}. */
  308.     private static final double F_13_14 = 13d / 14d;
  309.     /** Constant: {@value}. */
  310.     private static final double F_11_12 = 11d / 12d;
  311.     /** Constant: {@value}. */
  312.     private static final double F_9_10 = 9d / 10d;
  313.     /** Constant: {@value}. */
  314.     private static final double F_7_8 = 7d / 8d;
  315.     /** Constant: {@value}. */
  316.     private static final double F_5_6 = 5d / 6d;
  317.     /** Constant: {@value}. */
  318.     private static final double F_1_2 = 1d / 2d;
  319.     /** Constant: {@value}. */
  320.     private static final double F_1_4 = 1d / 4d;

  321.     /**
  322.      * Private Constructor.
  323.      */
  324.     private AccurateMath() {}

  325.     // Generic helper methods

  326.     /**
  327.      * Get the high order bits from the mantissa.
  328.      * Equivalent to adding and subtracting HEX_40000 but also works for very large numbers
  329.      *
  330.      * @param d the value to split
  331.      * @return the high order part of the mantissa
  332.      */
  333.     private static double doubleHighPart(double d) {
  334.         if (d > -Precision.SAFE_MIN && d < Precision.SAFE_MIN) {
  335.             return d; // These are un-normalised - don't try to convert
  336.         }
  337.         long xl = Double.doubleToRawLongBits(d); // can take raw bits because just gonna convert it back
  338.         xl &= MASK_30BITS; // Drop low order bits
  339.         return Double.longBitsToDouble(xl);
  340.     }

  341.     /** Compute the hyperbolic cosine of a number.
  342.      * @param x number on which evaluation is done
  343.      * @return hyperbolic cosine of x
  344.      */
  345.     public static double cosh(double x) {
  346.         if (Double.isNaN(x)) {
  347.             return x;
  348.         }

  349.         // cosh[z] = (exp(z) + exp(-z))/2

  350.         // for numbers with magnitude 20 or so,
  351.         // exp(-z) can be ignored in comparison with exp(z)

  352.         if (x > 20) {
  353.             if (x >= LOG_MAX_VALUE) {
  354.                 // Avoid overflow (MATH-905).
  355.                 final double t = exp(0.5 * x);
  356.                 return (0.5 * t) * t;
  357.             } else {
  358.                 return 0.5 * exp(x);
  359.             }
  360.         } else if (x < -20) {
  361.             if (x <= -LOG_MAX_VALUE) {
  362.                 // Avoid overflow (MATH-905).
  363.                 final double t = exp(-0.5 * x);
  364.                 return (0.5 * t) * t;
  365.             } else {
  366.                 return 0.5 * exp(-x);
  367.             }
  368.         }

  369.         final double[] hiPrec = new double[2];
  370.         if (x < 0.0) {
  371.             x = -x;
  372.         }
  373.         exp(x, 0.0, hiPrec);

  374.         double ya = hiPrec[0] + hiPrec[1];
  375.         double yb = -(ya - hiPrec[0] - hiPrec[1]);

  376.         double temp = ya * HEX_40000000;
  377.         double yaa = ya + temp - temp;
  378.         double yab = ya - yaa;

  379.         // recip = 1/y
  380.         double recip = 1.0 / ya;
  381.         temp = recip * HEX_40000000;
  382.         double recipa = recip + temp - temp;
  383.         double recipb = recip - recipa;

  384.         // Correct for rounding in division
  385.         recipb += (1.0 - yaa * recipa - yaa * recipb - yab * recipa - yab * recipb) * recip;
  386.         // Account for yb
  387.         recipb += -yb * recip * recip;

  388.         // y = y + 1/y
  389.         temp = ya + recipa;
  390.         yb += -(temp - ya - recipa);
  391.         ya = temp;
  392.         temp = ya + recipb;
  393.         yb += -(temp - ya - recipb);
  394.         ya = temp;

  395.         double result = ya + yb;
  396.         result *= 0.5;
  397.         return result;
  398.     }

  399.     /** Compute the hyperbolic sine of a number.
  400.      * @param x number on which evaluation is done
  401.      * @return hyperbolic sine of x
  402.      */
  403.     public static double sinh(double x) {
  404.         boolean negate = false;
  405.         if (Double.isNaN(x)) {
  406.             return x;
  407.         }

  408.         // sinh[z] = (exp(z) - exp(-z) / 2

  409.         // for values of z larger than about 20,
  410.         // exp(-z) can be ignored in comparison with exp(z)

  411.         if (x > 20) {
  412.             if (x >= LOG_MAX_VALUE) {
  413.                 // Avoid overflow (MATH-905).
  414.                 final double t = exp(0.5 * x);
  415.                 return (0.5 * t) * t;
  416.             } else {
  417.                 return 0.5 * exp(x);
  418.             }
  419.         } else if (x < -20) {
  420.             if (x <= -LOG_MAX_VALUE) {
  421.                 // Avoid overflow (MATH-905).
  422.                 final double t = exp(-0.5 * x);
  423.                 return (-0.5 * t) * t;
  424.             } else {
  425.                 return -0.5 * exp(-x);
  426.             }
  427.         }

  428.         if (x == 0) {
  429.             return x;
  430.         }

  431.         if (x < 0.0) {
  432.             x = -x;
  433.             negate = true;
  434.         }

  435.         double result;

  436.         if (x > 0.25) {
  437.             double[] hiPrec = new double[2];
  438.             exp(x, 0.0, hiPrec);

  439.             double ya = hiPrec[0] + hiPrec[1];
  440.             double yb = -(ya - hiPrec[0] - hiPrec[1]);

  441.             double temp = ya * HEX_40000000;
  442.             double yaa = ya + temp - temp;
  443.             double yab = ya - yaa;

  444.             // recip = 1/y
  445.             double recip = 1.0 / ya;
  446.             temp = recip * HEX_40000000;
  447.             double recipa = recip + temp - temp;
  448.             double recipb = recip - recipa;

  449.             // Correct for rounding in division
  450.             recipb += (1.0 - yaa * recipa - yaa * recipb - yab * recipa - yab * recipb) * recip;
  451.             // Account for yb
  452.             recipb += -yb * recip * recip;

  453.             recipa = -recipa;
  454.             recipb = -recipb;

  455.             // y = y + 1/y
  456.             temp = ya + recipa;
  457.             yb += -(temp - ya - recipa);
  458.             ya = temp;
  459.             temp = ya + recipb;
  460.             yb += -(temp - ya - recipb);
  461.             ya = temp;

  462.             result = ya + yb;
  463.             result *= 0.5;
  464.         } else {
  465.             double[] hiPrec = new double[2];
  466.             expm1(x, hiPrec);

  467.             double ya = hiPrec[0] + hiPrec[1];
  468.             double yb = -(ya - hiPrec[0] - hiPrec[1]);

  469.             /* Compute expm1(-x) = -expm1(x) / (expm1(x) + 1) */
  470.             double denom = 1.0 + ya;
  471.             double denomr = 1.0 / denom;
  472.             double denomb = -(denom - 1.0 - ya) + yb;
  473.             double ratio = ya * denomr;
  474.             double temp = ratio * HEX_40000000;
  475.             double ra = ratio + temp - temp;
  476.             double rb = ratio - ra;

  477.             temp = denom * HEX_40000000;
  478.             double za = denom + temp - temp;
  479.             double zb = denom - za;

  480.             rb += (ya - za * ra - za * rb - zb * ra - zb * rb) * denomr;

  481.             // Adjust for yb
  482.             rb += yb * denomr;                      // numerator
  483.             rb += -ya * denomb * denomr * denomr;   // denominator

  484.             // y = y - 1/y
  485.             temp = ya + ra;
  486.             yb += -(temp - ya - ra);
  487.             ya = temp;
  488.             temp = ya + rb;
  489.             yb += -(temp - ya - rb);
  490.             ya = temp;

  491.             result = ya + yb;
  492.             result *= 0.5;
  493.         }

  494.         if (negate) {
  495.             result = -result;
  496.         }

  497.         return result;
  498.     }

  499.     /** Compute the hyperbolic tangent of a number.
  500.      * @param x number on which evaluation is done
  501.      * @return hyperbolic tangent of x
  502.      */
  503.     public static double tanh(double x) {
  504.         boolean negate = false;

  505.         if (Double.isNaN(x)) {
  506.             return x;
  507.         }

  508.         // tanh[z] = sinh[z] / cosh[z]
  509.         // = (exp(z) - exp(-z)) / (exp(z) + exp(-z))
  510.         // = (exp(2x) - 1) / (exp(2x) + 1)

  511.         // for magnitude > 20, sinh[z] == cosh[z] in double precision

  512.         if (x > 20.0) {
  513.             return 1.0;
  514.         }

  515.         if (x < -20) {
  516.             return -1.0;
  517.         }

  518.         if (x == 0) {
  519.             return x;
  520.         }

  521.         if (x < 0.0) {
  522.             x = -x;
  523.             negate = true;
  524.         }

  525.         double result;
  526.         if (x >= 0.5) {
  527.             double[] hiPrec = new double[2];
  528.             // tanh(x) = (exp(2x) - 1) / (exp(2x) + 1)
  529.             exp(x * 2.0, 0.0, hiPrec);

  530.             double ya = hiPrec[0] + hiPrec[1];
  531.             double yb = -(ya - hiPrec[0] - hiPrec[1]);

  532.             /* Numerator */
  533.             double na = -1.0 + ya;
  534.             double nb = -(na + 1.0 - ya);
  535.             double temp = na + yb;
  536.             nb += -(temp - na - yb);
  537.             na = temp;

  538.             /* Denominator */
  539.             double da = 1.0 + ya;
  540.             double db = -(da - 1.0 - ya);
  541.             temp = da + yb;
  542.             db += -(temp - da - yb);
  543.             da = temp;

  544.             temp = da * HEX_40000000;
  545.             double daa = da + temp - temp;
  546.             double dab = da - daa;

  547.             // ratio = na/da
  548.             double ratio = na / da;
  549.             temp = ratio * HEX_40000000;
  550.             double ratioa = ratio + temp - temp;
  551.             double ratiob = ratio - ratioa;

  552.             // Correct for rounding in division
  553.             ratiob += (na - daa * ratioa - daa * ratiob - dab * ratioa - dab * ratiob) / da;

  554.             // Account for nb
  555.             ratiob += nb / da;
  556.             // Account for db
  557.             ratiob += -db * na / da / da;

  558.             result = ratioa + ratiob;
  559.         } else {
  560.             double[] hiPrec = new double[2];
  561.             // tanh(x) = expm1(2x) / (expm1(2x) + 2)
  562.             expm1(x * 2.0, hiPrec);

  563.             double ya = hiPrec[0] + hiPrec[1];
  564.             double yb = -(ya - hiPrec[0] - hiPrec[1]);

  565.             /* Numerator */
  566.             double na = ya;
  567.             double nb = yb;

  568.             /* Denominator */
  569.             double da = 2.0 + ya;
  570.             double db = -(da - 2.0 - ya);
  571.             double temp = da + yb;
  572.             db += -(temp - da - yb);
  573.             da = temp;

  574.             temp = da * HEX_40000000;
  575.             double daa = da + temp - temp;
  576.             double dab = da - daa;

  577.             // ratio = na/da
  578.             double ratio = na / da;
  579.             temp = ratio * HEX_40000000;
  580.             double ratioa = ratio + temp - temp;
  581.             double ratiob = ratio - ratioa;

  582.             // Correct for rounding in division
  583.             ratiob += (na - daa * ratioa - daa * ratiob - dab * ratioa - dab * ratiob) / da;

  584.             // Account for nb
  585.             ratiob += nb / da;
  586.             // Account for db
  587.             ratiob += -db * na / da / da;

  588.             result = ratioa + ratiob;
  589.         }

  590.         if (negate) {
  591.             result = -result;
  592.         }

  593.         return result;
  594.     }

  595.     /** Compute the inverse hyperbolic cosine of a number.
  596.      * @param a number on which evaluation is done
  597.      * @return inverse hyperbolic cosine of a
  598.      */
  599.     public static double acosh(final double a) {
  600.         return AccurateMath.log(a + Math.sqrt(a * a - 1));
  601.     }

  602.     /** Compute the inverse hyperbolic sine of a number.
  603.      * @param a number on which evaluation is done
  604.      * @return inverse hyperbolic sine of a
  605.      */
  606.     public static double asinh(double a) {
  607.         boolean negative = false;
  608.         if (a < 0) {
  609.             negative = true;
  610.             a = -a;
  611.         }

  612.         double absAsinh;
  613.         if (a > 0.167) {
  614.             absAsinh = AccurateMath.log(Math.sqrt(a * a + 1) + a);
  615.         } else {
  616.             final double a2 = a * a;
  617.             if (a > 0.097) {
  618.                 absAsinh = a * (1 - a2 * (F_1_3 - a2 * (F_1_5 - a2 * (F_1_7 - a2 * (F_1_9 - a2 * (F_1_11 - a2 * (F_1_13 - a2 * (F_1_15 - a2 * F_1_17 * F_15_16) * F_13_14) * F_11_12) * F_9_10) * F_7_8) * F_5_6) * F_3_4) * F_1_2);
  619.             } else if (a > 0.036) {
  620.                 absAsinh = a * (1 - a2 * (F_1_3 - a2 * (F_1_5 - a2 * (F_1_7 - a2 * (F_1_9 - a2 * (F_1_11 - a2 * F_1_13 * F_11_12) * F_9_10) * F_7_8) * F_5_6) * F_3_4) * F_1_2);
  621.             } else if (a > 0.0036) {
  622.                 absAsinh = a * (1 - a2 * (F_1_3 - a2 * (F_1_5 - a2 * (F_1_7 - a2 * F_1_9 * F_7_8) * F_5_6) * F_3_4) * F_1_2);
  623.             } else {
  624.                 absAsinh = a * (1 - a2 * (F_1_3 - a2 * F_1_5 * F_3_4) * F_1_2);
  625.             }
  626.         }

  627.         return negative ? -absAsinh : absAsinh;
  628.     }

  629.     /** Compute the inverse hyperbolic tangent of a number.
  630.      * @param a number on which evaluation is done
  631.      * @return inverse hyperbolic tangent of a
  632.      */
  633.     public static double atanh(double a) {
  634.         boolean negative = false;
  635.         if (a < 0) {
  636.             negative = true;
  637.             a = -a;
  638.         }

  639.         double absAtanh;
  640.         if (a > 0.15) {
  641.             absAtanh = 0.5 * AccurateMath.log((1 + a) / (1 - a));
  642.         } else {
  643.             final double a2 = a * a;
  644.             if (a > 0.087) {
  645.                 absAtanh = a * (1 + a2 * (F_1_3 + a2 * (F_1_5 + a2 * (F_1_7 + a2 * (F_1_9 + a2 * (F_1_11 + a2 * (F_1_13 + a2 * (F_1_15 + a2 * F_1_17))))))));
  646.             } else if (a > 0.031) {
  647.                 absAtanh = a * (1 + a2 * (F_1_3 + a2 * (F_1_5 + a2 * (F_1_7 + a2 * (F_1_9 + a2 * (F_1_11 + a2 * F_1_13))))));
  648.             } else if (a > 0.003) {
  649.                 absAtanh = a * (1 + a2 * (F_1_3 + a2 * (F_1_5 + a2 * (F_1_7 + a2 * F_1_9))));
  650.             } else {
  651.                 absAtanh = a * (1 + a2 * (F_1_3 + a2 * F_1_5));
  652.             }
  653.         }

  654.         return negative ? -absAtanh : absAtanh;
  655.     }

  656.     /** Compute the signum of a number.
  657.      * The signum is -1 for negative numbers, +1 for positive numbers and 0 otherwise
  658.      * @param a number on which evaluation is done
  659.      * @return -1.0, -0.0, +0.0, +1.0 or NaN depending on sign of a
  660.      */
  661.     public static double signum(final double a) {
  662.         return (a < 0.0) ? -1.0 : ((a > 0.0) ? 1.0 : a); // return +0.0/-0.0/NaN depending on a
  663.     }

  664.     /** Compute the signum of a number.
  665.      * The signum is -1 for negative numbers, +1 for positive numbers and 0 otherwise
  666.      * @param a number on which evaluation is done
  667.      * @return -1.0, -0.0, +0.0, +1.0 or NaN depending on sign of a
  668.      */
  669.     public static float signum(final float a) {
  670.         return (a < 0.0f) ? -1.0f : ((a > 0.0f) ? 1.0f : a); // return +0.0/-0.0/NaN depending on a
  671.     }

  672.     /** Compute next number towards positive infinity.
  673.      * @param a number to which neighbor should be computed
  674.      * @return neighbor of a towards positive infinity
  675.      */
  676.     public static double nextUp(final double a) {
  677.         return nextAfter(a, Double.POSITIVE_INFINITY);
  678.     }

  679.     /** Compute next number towards positive infinity.
  680.      * @param a number to which neighbor should be computed
  681.      * @return neighbor of a towards positive infinity
  682.      */
  683.     public static float nextUp(final float a) {
  684.         return nextAfter(a, Float.POSITIVE_INFINITY);
  685.     }

  686.     /** Compute next number towards negative infinity.
  687.      * @param a number to which neighbor should be computed
  688.      * @return neighbor of a towards negative infinity
  689.      * @since 3.4
  690.      */
  691.     public static double nextDown(final double a) {
  692.         return nextAfter(a, Double.NEGATIVE_INFINITY);
  693.     }

  694.     /** Compute next number towards negative infinity.
  695.      * @param a number to which neighbor should be computed
  696.      * @return neighbor of a towards negative infinity
  697.      * @since 3.4
  698.      */
  699.     public static float nextDown(final float a) {
  700.         return nextAfter(a, Float.NEGATIVE_INFINITY);
  701.     }

  702.     /**
  703.      * Exponential function.
  704.      *
  705.      * Computes exp(x), function result is nearly rounded.   It will be correctly
  706.      * rounded to the theoretical value for 99.9% of input values, otherwise it will
  707.      * have a 1 ULP error.
  708.      *
  709.      * Method:
  710.      *    Lookup intVal = exp(int(x))
  711.      *    Lookup fracVal = exp(int(x-int(x) / 1024.0) * 1024.0 );
  712.      *    Compute z as the exponential of the remaining bits by a polynomial minus one
  713.      *    exp(x) = intVal * fracVal * (1 + z)
  714.      *
  715.      * Accuracy:
  716.      *    Calculation is done with 63 bits of precision, so result should be correctly
  717.      *    rounded for 99.9% of input values, with less than 1 ULP error otherwise.
  718.      *
  719.      * @param x   a double
  720.      * @return double e<sup>x</sup>
  721.      */
  722.     public static double exp(double x) {
  723.         return exp(x, 0.0, null);
  724.     }

  725.     /**
  726.      * Internal helper method for exponential function.
  727.      * @param x original argument of the exponential function
  728.      * @param extra extra bits of precision on input (To Be Confirmed)
  729.      * @param hiPrec extra bits of precision on output (To Be Confirmed)
  730.      * @return exp(x)
  731.      */
  732.     private static double exp(double x, double extra, double[] hiPrec) {
  733.         double intPartA;
  734.         double intPartB;
  735.         int intVal = (int) x;

  736.         /* Lookup exp(floor(x)).
  737.          * intPartA will have the upper 22 bits, intPartB will have the lower
  738.          * 52 bits.
  739.          */
  740.         if (x < 0.0) {

  741.             // We don't check against intVal here as conversion of large negative double values
  742.             // may be affected by a JIT bug. Subsequent comparisons can safely use intVal
  743.             if (x < -746d) {
  744.                 if (hiPrec != null) {
  745.                     hiPrec[0] = 0.0;
  746.                     hiPrec[1] = 0.0;
  747.                 }
  748.                 return 0.0;
  749.             }

  750.             if (intVal < -709) {
  751.                 /* This will produce a subnormal output */
  752.                 final double result = exp(x + 40.19140625, extra, hiPrec) / 285040095144011776.0;
  753.                 if (hiPrec != null) {
  754.                     hiPrec[0] /= 285040095144011776.0;
  755.                     hiPrec[1] /= 285040095144011776.0;
  756.                 }
  757.                 return result;
  758.             }

  759.             if (intVal == -709) {
  760.                 /* exp(1.494140625) is nearly a machine number... */
  761.                 final double result = exp(x + 1.494140625, extra, hiPrec) / 4.455505956692756620;
  762.                 if (hiPrec != null) {
  763.                     hiPrec[0] /= 4.455505956692756620;
  764.                     hiPrec[1] /= 4.455505956692756620;
  765.                 }
  766.                 return result;
  767.             }

  768.             intVal--;
  769.         } else {
  770.             if (intVal > 709) {
  771.                 if (hiPrec != null) {
  772.                     hiPrec[0] = Double.POSITIVE_INFINITY;
  773.                     hiPrec[1] = 0.0;
  774.                 }
  775.                 return Double.POSITIVE_INFINITY;
  776.             }
  777.         }

  778.         intPartA = ExpIntTable.EXP_INT_TABLE_A[EXP_INT_TABLE_MAX_INDEX + intVal];
  779.         intPartB = ExpIntTable.EXP_INT_TABLE_B[EXP_INT_TABLE_MAX_INDEX + intVal];

  780.         /* Get the fractional part of x, find the greatest multiple of 2^-10 less than
  781.          * x and look up the exp function of it.
  782.          * fracPartA will have the upper 22 bits, fracPartB the lower 52 bits.
  783.          */
  784.         final int intFrac = (int) ((x - intVal) * 1024.0);
  785.         final double fracPartA = ExpFracTable.EXP_FRAC_TABLE_A[intFrac];
  786.         final double fracPartB = ExpFracTable.EXP_FRAC_TABLE_B[intFrac];

  787.         /* epsilon is the difference in x from the nearest multiple of 2^-10.  It
  788.          * has a value in the range 0 <= epsilon < 2^-10.
  789.          * Do the subtraction from x as the last step to avoid possible loss of precision.
  790.          */
  791.         final double epsilon = x - (intVal + intFrac / 1024.0);

  792.         /* Compute z = exp(epsilon) - 1.0 via a minimax polynomial.  z has
  793.        full double precision (52 bits).  Since z < 2^-10, we will have
  794.        62 bits of precision when combined with the constant 1.  This will be
  795.        used in the last addition below to get proper rounding. */

  796.         /* Remez generated polynomial.  Converges on the interval [0, 2^-10], error
  797.        is less than 0.5 ULP */
  798.         double z = 0.04168701738764507;
  799.         z = z * epsilon + 0.1666666505023083;
  800.         z = z * epsilon + 0.5000000000042687;
  801.         z = z * epsilon + 1.0;
  802.         z = z * epsilon + -3.940510424527919E-20;

  803.         /* Compute (intPartA+intPartB) * (fracPartA+fracPartB) by binomial
  804.        expansion.
  805.        tempA is exact since intPartA and intPartB only have 22 bits each.
  806.        tempB will have 52 bits of precision.
  807.          */
  808.         double tempA = intPartA * fracPartA;
  809.         double tempB = intPartA * fracPartB + intPartB * fracPartA + intPartB * fracPartB;

  810.         /* Compute the result.  (1+z)(tempA+tempB).  Order of operations is
  811.        important.  For accuracy add by increasing size.  tempA is exact and
  812.        much larger than the others.  If there are extra bits specified from the
  813.        pow() function, use them. */
  814.         final double tempC = tempB + tempA;

  815.         // If tempC is positive infinite, the evaluation below could result in NaN,
  816.         // because z could be negative at the same time.
  817.         if (tempC == Double.POSITIVE_INFINITY) {
  818.             return Double.POSITIVE_INFINITY;
  819.         }

  820.         final double result;
  821.         if (extra != 0.0) {
  822.             result = tempC * extra * z + tempC * extra + tempC * z + tempB + tempA;
  823.         } else {
  824.             result = tempC * z + tempB + tempA;
  825.         }

  826.         if (hiPrec != null) {
  827.             // If requesting high precision
  828.             hiPrec[0] = tempA;
  829.             hiPrec[1] = tempC * extra * z + tempC * extra + tempC * z + tempB;
  830.         }

  831.         return result;
  832.     }

  833.     /**Compute exp(x) - 1.
  834.      *
  835.      * @param x number to compute shifted exponential
  836.      * @return exp(x) - 1
  837.      */
  838.     public static double expm1(double x) {
  839.         return expm1(x, null);
  840.     }

  841.     /** Internal helper method for expm1.
  842.      * @param x number to compute shifted exponential
  843.      * @param hiPrecOut receive high precision result for -1.0 < x < 1.0
  844.      * @return exp(x) - 1
  845.      */
  846.     private static double expm1(double x, double[] hiPrecOut) {
  847.         if (Double.isNaN(x) || x == 0.0) { // NaN or zero
  848.             return x;
  849.         }

  850.         if (x <= -1.0 || x >= 1.0) {
  851.             // If not between +/- 1.0
  852.             //return exp(x) - 1.0;
  853.             double[] hiPrec = new double[2];
  854.             exp(x, 0.0, hiPrec);
  855.             if (x > 0.0) {
  856.                 return -1.0 + hiPrec[0] + hiPrec[1];
  857.             } else {
  858.                 final double ra = -1.0 + hiPrec[0];
  859.                 double rb = -(ra + 1.0 - hiPrec[0]);
  860.                 rb += hiPrec[1];
  861.                 return ra + rb;
  862.             }
  863.         }

  864.         double baseA;
  865.         double baseB;
  866.         double epsilon;
  867.         boolean negative = false;

  868.         if (x < 0.0) {
  869.             x = -x;
  870.             negative = true;
  871.         }

  872.         int intFrac = (int) (x * 1024.0);
  873.         double tempA = ExpFracTable.EXP_FRAC_TABLE_A[intFrac] - 1.0;
  874.         double tempB = ExpFracTable.EXP_FRAC_TABLE_B[intFrac];

  875.         double temp = tempA + tempB;
  876.         tempB = -(temp - tempA - tempB);
  877.         tempA = temp;

  878.         temp = tempA * HEX_40000000;
  879.         baseA = tempA + temp - temp;
  880.         baseB = tempB + (tempA - baseA);

  881.         epsilon = x - intFrac / 1024.0;


  882.         /* Compute expm1(epsilon) */
  883.         double zb = 0.008336750013465571;
  884.         zb = zb * epsilon + 0.041666663879186654;
  885.         zb = zb * epsilon + 0.16666666666745392;
  886.         zb = zb * epsilon + 0.49999999999999994;
  887.         zb *= epsilon;
  888.         zb *= epsilon;

  889.         double za = epsilon;
  890.         temp = za + zb;
  891.         zb = -(temp - za - zb);
  892.         za = temp;

  893.         temp = za * HEX_40000000;
  894.         temp = za + temp - temp;
  895.         zb += za - temp;
  896.         za = temp;

  897.         /* Combine the parts.   expm1(a+b) = expm1(a) + expm1(b) + expm1(a)*expm1(b) */
  898.         double ya = za * baseA;
  899.         //double yb = za*baseB + zb*baseA + zb*baseB;
  900.         temp = ya + za * baseB;
  901.         double yb = -(temp - ya - za * baseB);
  902.         ya = temp;

  903.         temp = ya + zb * baseA;
  904.         yb += -(temp - ya - zb * baseA);
  905.         ya = temp;

  906.         temp = ya + zb * baseB;
  907.         yb += -(temp - ya - zb * baseB);
  908.         ya = temp;

  909.         //ya = ya + za + baseA;
  910.         //yb = yb + zb + baseB;
  911.         temp = ya + baseA;
  912.         yb += -(temp - baseA - ya);
  913.         ya = temp;

  914.         temp = ya + za;
  915.         //yb += (ya > za) ? -(temp - ya - za) : -(temp - za - ya);
  916.         yb += -(temp - ya - za);
  917.         ya = temp;

  918.         temp = ya + baseB;
  919.         //yb += (ya > baseB) ? -(temp - ya - baseB) : -(temp - baseB - ya);
  920.         yb += -(temp - ya - baseB);
  921.         ya = temp;

  922.         temp = ya + zb;
  923.         //yb += (ya > zb) ? -(temp - ya - zb) : -(temp - zb - ya);
  924.         yb += -(temp - ya - zb);
  925.         ya = temp;

  926.         if (negative) {
  927.             /* Compute expm1(-x) = -expm1(x) / (expm1(x) + 1) */
  928.             double denom = 1.0 + ya;
  929.             double denomr = 1.0 / denom;
  930.             double denomb = -(denom - 1.0 - ya) + yb;
  931.             double ratio = ya * denomr;
  932.             temp = ratio * HEX_40000000;
  933.             final double ra = ratio + temp - temp;
  934.             double rb = ratio - ra;

  935.             temp = denom * HEX_40000000;
  936.             za = denom + temp - temp;
  937.             zb = denom - za;

  938.             rb += (ya - za * ra - za * rb - zb * ra - zb * rb) * denomr;

  939.             // f(x) = x/1+x
  940.             // Compute f'(x)
  941.             // Product rule:  d(uv) = du*v + u*dv
  942.             // Chain rule:  d(f(g(x)) = f'(g(x))*f(g'(x))
  943.             // d(1/x) = -1/(x*x)
  944.             // d(1/1+x) = -1/( (1+x)^2) *  1 =  -1/((1+x)*(1+x))
  945.             // d(x/1+x) = -x/((1+x)(1+x)) + 1/1+x = 1 / ((1+x)(1+x))

  946.             // Adjust for yb
  947.             rb += yb * denomr;                      // numerator
  948.             rb += -ya * denomb * denomr * denomr;   // denominator

  949.             // negate
  950.             ya = -ra;
  951.             yb = -rb;
  952.         }

  953.         if (hiPrecOut != null) {
  954.             hiPrecOut[0] = ya;
  955.             hiPrecOut[1] = yb;
  956.         }

  957.         return ya + yb;
  958.     }

  959.     /**
  960.      * Natural logarithm.
  961.      *
  962.      * @param x   a double
  963.      * @return log(x)
  964.      */
  965.     public static double log(final double x) {
  966.         return log(x, null);
  967.     }

  968.     /**
  969.      * Internal helper method for natural logarithm function.
  970.      * @param x original argument of the natural logarithm function
  971.      * @param hiPrec extra bits of precision on output (To Be Confirmed)
  972.      * @return log(x)
  973.      */
  974.     private static double log(final double x, final double[] hiPrec) {
  975.         if (x == 0) { // Handle special case of +0/-0
  976.             return Double.NEGATIVE_INFINITY;
  977.         }
  978.         long bits = Double.doubleToRawLongBits(x);

  979.         /* Handle special cases of negative input, and NaN */
  980.         if (((bits & 0x8000000000000000L) != 0 || Double.isNaN(x)) && x != 0.0) {
  981.             if (hiPrec != null) {
  982.                 hiPrec[0] = Double.NaN;
  983.             }

  984.             return Double.NaN;
  985.         }

  986.         /* Handle special cases of Positive infinity. */
  987.         if (x == Double.POSITIVE_INFINITY) {
  988.             if (hiPrec != null) {
  989.                 hiPrec[0] = Double.POSITIVE_INFINITY;
  990.             }

  991.             return Double.POSITIVE_INFINITY;
  992.         }

  993.         /* Extract the exponent */
  994.         int exp = (int) (bits >> 52) - 1023;

  995.         if ((bits & 0x7ff0000000000000L) == 0) {
  996.             // Subnormal!
  997.             if (x == 0) {
  998.                 // Zero
  999.                 if (hiPrec != null) {
  1000.                     hiPrec[0] = Double.NEGATIVE_INFINITY;
  1001.                 }

  1002.                 return Double.NEGATIVE_INFINITY;
  1003.             }

  1004.             /* Normalize the subnormal number. */
  1005.             bits <<= 1;
  1006.             while ((bits & 0x0010000000000000L) == 0) {
  1007.                 --exp;
  1008.                 bits <<= 1;
  1009.             }
  1010.         }


  1011.         if ((exp == -1 || exp == 0) && x < 1.01 && x > 0.99 && hiPrec == null) {
  1012.             /* The normal method doesn't work well in the range [0.99, 1.01], so call do a straight
  1013.            polynomial expansion in higer precision. */

  1014.             /* Compute x - 1.0 and split it */
  1015.             double xa = x - 1.0;
  1016.             double xb = xa - x + 1.0;
  1017.             double tmp = xa * HEX_40000000;
  1018.             double aa = xa + tmp - tmp;
  1019.             double ab = xa - aa;
  1020.             xa = aa;
  1021.             xb = ab;

  1022.             final double[] lnCoef_last = LN_QUICK_COEF[LN_QUICK_COEF.length - 1];
  1023.             double ya = lnCoef_last[0];
  1024.             double yb = lnCoef_last[1];

  1025.             for (int i = LN_QUICK_COEF.length - 2; i >= 0; i--) {
  1026.                 /* Multiply a = y * x */
  1027.                 aa = ya * xa;
  1028.                 ab = ya * xb + yb * xa + yb * xb;
  1029.                 /* split, so now y = a */
  1030.                 tmp = aa * HEX_40000000;
  1031.                 ya = aa + tmp - tmp;
  1032.                 yb = aa - ya + ab;

  1033.                 /* Add  a = y + lnQuickCoef */
  1034.                 final double[] lnCoef_i = LN_QUICK_COEF[i];
  1035.                 aa = ya + lnCoef_i[0];
  1036.                 ab = yb + lnCoef_i[1];
  1037.                 /* Split y = a */
  1038.                 tmp = aa * HEX_40000000;
  1039.                 ya = aa + tmp - tmp;
  1040.                 yb = aa - ya + ab;
  1041.             }

  1042.             /* Multiply a = y * x */
  1043.             aa = ya * xa;
  1044.             ab = ya * xb + yb * xa + yb * xb;
  1045.             /* split, so now y = a */
  1046.             tmp = aa * HEX_40000000;
  1047.             ya = aa + tmp - tmp;
  1048.             yb = aa - ya + ab;

  1049.             return ya + yb;
  1050.         }

  1051.         // lnm is a log of a number in the range of 1.0 - 2.0, so 0 <= lnm < ln(2)
  1052.         final double[] lnm = lnMant.LN_MANT[(int)((bits & 0x000ffc0000000000L) >> 42)];

  1053.         /*
  1054.     double epsilon = x / Double.longBitsToDouble(bits & 0xfffffc0000000000L);

  1055.     epsilon -= 1.0;
  1056.          */

  1057.         // y is the most significant 10 bits of the mantissa
  1058.         //double y = Double.longBitsToDouble(bits & 0xfffffc0000000000L);
  1059.         //double epsilon = (x - y) / y;
  1060.         final double epsilon = (bits & 0x3ffffffffffL) / (TWO_POWER_52 + (bits & 0x000ffc0000000000L));

  1061.         double lnza = 0.0;
  1062.         double lnzb = 0.0;

  1063.         if (hiPrec != null) {
  1064.             /* split epsilon -> x */
  1065.             double tmp = epsilon * HEX_40000000;
  1066.             double aa = epsilon + tmp - tmp;
  1067.             double ab = epsilon - aa;
  1068.             double xa = aa;
  1069.             double xb = ab;

  1070.             /* Need a more accurate epsilon, so adjust the division. */
  1071.             final double numer = bits & 0x3ffffffffffL;
  1072.             final double denom = TWO_POWER_52 + (bits & 0x000ffc0000000000L);
  1073.             aa = numer - xa * denom - xb * denom;
  1074.             xb += aa / denom;

  1075.             /* Remez polynomial evaluation */
  1076.             final double[] lnCoef_last = LN_HI_PREC_COEF[LN_HI_PREC_COEF.length - 1];
  1077.             double ya = lnCoef_last[0];
  1078.             double yb = lnCoef_last[1];

  1079.             for (int i = LN_HI_PREC_COEF.length - 2; i >= 0; i--) {
  1080.                 /* Multiply a = y * x */
  1081.                 aa = ya * xa;
  1082.                 ab = ya * xb + yb * xa + yb * xb;
  1083.                 /* split, so now y = a */
  1084.                 tmp = aa * HEX_40000000;
  1085.                 ya = aa + tmp - tmp;
  1086.                 yb = aa - ya + ab;

  1087.                 /* Add  a = y + lnHiPrecCoef */
  1088.                 final double[] lnCoef_i = LN_HI_PREC_COEF[i];
  1089.                 aa = ya + lnCoef_i[0];
  1090.                 ab = yb + lnCoef_i[1];
  1091.                 /* Split y = a */
  1092.                 tmp = aa * HEX_40000000;
  1093.                 ya = aa + tmp - tmp;
  1094.                 yb = aa - ya + ab;
  1095.             }

  1096.             /* Multiply a = y * x */
  1097.             aa = ya * xa;
  1098.             ab = ya * xb + yb * xa + yb * xb;

  1099.             /* split, so now lnz = a */
  1100.             /*
  1101.       tmp = aa * 1073741824.0;
  1102.       lnza = aa + tmp - tmp;
  1103.       lnzb = aa - lnza + ab;
  1104.              */
  1105.             lnza = aa + ab;
  1106.             lnzb = -(lnza - aa - ab);
  1107.         } else {
  1108.             /* High precision not required.  Eval Remez polynomial
  1109.          using standard double precision */
  1110.             lnza = -0.16624882440418567;
  1111.             lnza = lnza * epsilon + 0.19999954120254515;
  1112.             lnza = lnza * epsilon + -0.2499999997677497;
  1113.             lnza = lnza * epsilon + 0.3333333333332802;
  1114.             lnza = lnza * epsilon + -0.5;
  1115.             lnza = lnza * epsilon + 1.0;
  1116.             lnza *= epsilon;
  1117.         }

  1118.         /* Relative sizes:
  1119.          * lnzb     [0, 2.33E-10]
  1120.          * lnm[1]   [0, 1.17E-7]
  1121.          * ln2B*exp [0, 1.12E-4]
  1122.          * lnza      [0, 9.7E-4]
  1123.          * lnm[0]   [0, 0.692]
  1124.          * ln2A*exp [0, 709]
  1125.          */

  1126.         /* Compute the following sum:
  1127.          * lnzb + lnm[1] + ln2B*exp + lnza + lnm[0] + ln2A*exp;
  1128.          */

  1129.         //return lnzb + lnm[1] + ln2B*exp + lnza + lnm[0] + ln2A*exp;
  1130.         double a = LN_2_A * exp;
  1131.         double b = 0.0;
  1132.         double c = a + lnm[0];
  1133.         double d = -(c - a - lnm[0]);
  1134.         a = c;
  1135.         b += d;

  1136.         c = a + lnza;
  1137.         d = -(c - a - lnza);
  1138.         a = c;
  1139.         b += d;

  1140.         c = a + LN_2_B * exp;
  1141.         d = -(c - a - LN_2_B * exp);
  1142.         a = c;
  1143.         b += d;

  1144.         c = a + lnm[1];
  1145.         d = -(c - a - lnm[1]);
  1146.         a = c;
  1147.         b += d;

  1148.         c = a + lnzb;
  1149.         d = -(c - a - lnzb);
  1150.         a = c;
  1151.         b += d;

  1152.         if (hiPrec != null) {
  1153.             hiPrec[0] = a;
  1154.             hiPrec[1] = b;
  1155.         }

  1156.         return a + b;
  1157.     }

  1158.     /**
  1159.      * Computes log(1 + x).
  1160.      *
  1161.      * @param x Number.
  1162.      * @return {@code log(1 + x)}.
  1163.      */
  1164.     public static double log1p(final double x) {
  1165.         if (x == -1) {
  1166.             return Double.NEGATIVE_INFINITY;
  1167.         }

  1168.         if (x == Double.POSITIVE_INFINITY) {
  1169.             return Double.POSITIVE_INFINITY;
  1170.         }

  1171.         if (x > 1e-6 ||
  1172.             x < -1e-6) {
  1173.             final double xpa = 1 + x;
  1174.             final double xpb = -(xpa - 1 - x);

  1175.             final double[] hiPrec = new double[2];
  1176.             final double lores = log(xpa, hiPrec);
  1177.             if (Double.isInfinite(lores)) { // Don't allow this to be converted to NaN
  1178.                 return lores;
  1179.             }

  1180.             // Do a taylor series expansion around xpa:
  1181.             //   f(x+y) = f(x) + f'(x) y + f''(x)/2 y^2
  1182.             final double fx1 = xpb / xpa;
  1183.             final double epsilon = 0.5 * fx1 + 1;
  1184.             return epsilon * fx1 + hiPrec[1] + hiPrec[0];
  1185.         } else {
  1186.             // Value is small |x| < 1e6, do a Taylor series centered on 1.
  1187.             final double y = (x * F_1_3 - F_1_2) * x + 1;
  1188.             return y * x;
  1189.         }
  1190.     }

  1191.     /** Compute the base 10 logarithm.
  1192.      * @param x a number
  1193.      * @return log10(x)
  1194.      */
  1195.     public static double log10(final double x) {
  1196.         final double[] hiPrec = new double[2];

  1197.         final double lores = log(x, hiPrec);
  1198.         if (Double.isInfinite(lores)) { // don't allow this to be converted to NaN
  1199.             return lores;
  1200.         }

  1201.         final double tmp = hiPrec[0] * HEX_40000000;
  1202.         final double lna = hiPrec[0] + tmp - tmp;
  1203.         final double lnb = hiPrec[0] - lna + hiPrec[1];

  1204.         final double rln10a = 0.4342944622039795;
  1205.         final double rln10b = 1.9699272335463627E-8;

  1206.         return rln10b * lnb + rln10b * lna + rln10a * lnb + rln10a * lna;
  1207.     }

  1208.     /**
  1209.      * Computes the <a href="http://mathworld.wolfram.com/Logarithm.html">
  1210.      * logarithm</a> in a given base.
  1211.      *
  1212.      * Returns {@code NaN} if either argument is negative.
  1213.      * If {@code base} is 0 and {@code x} is positive, 0 is returned.
  1214.      * If {@code base} is positive and {@code x} is 0,
  1215.      * {@code Double.NEGATIVE_INFINITY} is returned.
  1216.      * If both arguments are 0, the result is {@code NaN}.
  1217.      *
  1218.      * @param base Base of the logarithm, must be greater than 0.
  1219.      * @param x Argument, must be greater than 0.
  1220.      * @return the value of the logarithm, i.e. the number {@code y} such that
  1221.      * <code>base<sup>y</sup> = x</code>.
  1222.      * @since 3.0
  1223.      */
  1224.     public static double log(double base, double x) {
  1225.         return log(x) / log(base);
  1226.     }

  1227.     /**
  1228.      * Power function.  Compute x^y.
  1229.      *
  1230.      * @param x   a double
  1231.      * @param y   a double
  1232.      * @return double
  1233.      */
  1234.     public static double pow(final double x, final double y) {

  1235.         if (y == 0) {
  1236.             // y = -0 or y = +0
  1237.             return 1.0;
  1238.         } else {

  1239.             final long yBits        = Double.doubleToRawLongBits(y);
  1240.             final int  yRawExp      = (int) ((yBits & MASK_DOUBLE_EXPONENT) >> 52);
  1241.             final long yRawMantissa = yBits & MASK_DOUBLE_MANTISSA;
  1242.             final long xBits        = Double.doubleToRawLongBits(x);
  1243.             final int  xRawExp      = (int) ((xBits & MASK_DOUBLE_EXPONENT) >> 52);
  1244.             final long xRawMantissa = xBits & MASK_DOUBLE_MANTISSA;

  1245.             if (yRawExp > 1085) {
  1246.                 // y is either a very large integral value that does not fit in a long or it is a special number

  1247.                 if ((yRawExp == 2047 && yRawMantissa != 0) ||
  1248.                     (xRawExp == 2047 && xRawMantissa != 0)) {
  1249.                     // NaN
  1250.                     return Double.NaN;
  1251.                 } else if (xRawExp == 1023 && xRawMantissa == 0) {
  1252.                     // x = -1.0 or x = +1.0
  1253.                     if (yRawExp == 2047) {
  1254.                         // y is infinite
  1255.                         return Double.NaN;
  1256.                     } else {
  1257.                         // y is a large even integer
  1258.                         return 1.0;
  1259.                     }
  1260.                 } else {
  1261.                     // the absolute value of x is either greater or smaller than 1.0

  1262.                     // if yRawExp == 2047 and mantissa is 0, y = -infinity or y = +infinity
  1263.                     // if 1085 < yRawExp < 2047, y is simply a large number, however, due to limited
  1264.                     // accuracy, at this magnitude it behaves just like infinity with regards to x
  1265.                     if ((y > 0) ^ (xRawExp < 1023)) {
  1266.                         // either y = +infinity (or large engouh) and abs(x) > 1.0
  1267.                         // or     y = -infinity (or large engouh) and abs(x) < 1.0
  1268.                         return Double.POSITIVE_INFINITY;
  1269.                     } else {
  1270.                         // either y = +infinity (or large engouh) and abs(x) < 1.0
  1271.                         // or     y = -infinity (or large engouh) and abs(x) > 1.0
  1272.                         return +0.0;
  1273.                     }
  1274.                 }
  1275.             } else {
  1276.                 // y is a regular non-zero number

  1277.                 if (yRawExp >= 1023) {
  1278.                     // y may be an integral value, which should be handled specifically
  1279.                     final long yFullMantissa = IMPLICIT_HIGH_BIT | yRawMantissa;
  1280.                     if (yRawExp < 1075) {
  1281.                         // normal number with negative shift that may have a fractional part
  1282.                         final long integralMask = (-1L) << (1075 - yRawExp);
  1283.                         if ((yFullMantissa & integralMask) == yFullMantissa) {
  1284.                             // all fractional bits are 0, the number is really integral
  1285.                             final long l = yFullMantissa >> (1075 - yRawExp);
  1286.                             return AccurateMath.pow(x, (y < 0) ? -l : l);
  1287.                         }
  1288.                     } else {
  1289.                         // normal number with positive shift, always an integral value
  1290.                         // we know it fits in a primitive long because yRawExp > 1085 has been handled above
  1291.                         final long l =  yFullMantissa << (yRawExp - 1075);
  1292.                         return AccurateMath.pow(x, (y < 0) ? -l : l);
  1293.                     }
  1294.                 }

  1295.                 // y is a non-integral value

  1296.                 if (x == 0) {
  1297.                     // x = -0 or x = +0
  1298.                     // the integer powers have already been handled above
  1299.                     return y < 0 ? Double.POSITIVE_INFINITY : +0.0;
  1300.                 } else if (xRawExp == 2047) {
  1301.                     if (xRawMantissa == 0) {
  1302.                         // x = -infinity or x = +infinity
  1303.                         return (y < 0) ? +0.0 : Double.POSITIVE_INFINITY;
  1304.                     } else {
  1305.                         // NaN
  1306.                         return Double.NaN;
  1307.                     }
  1308.                 } else if (x < 0) {
  1309.                     // the integer powers have already been handled above
  1310.                     return Double.NaN;
  1311.                 } else {

  1312.                     // this is the general case, for regular fractional numbers x and y

  1313.                     // Split y into ya and yb such that y = ya+yb
  1314.                     final double tmp = y * HEX_40000000;
  1315.                     final double ya = (y + tmp) - tmp;
  1316.                     final double yb = y - ya;

  1317.                     /* Compute ln(x) */
  1318.                     final double[] lns = new double[2];
  1319.                     final double lores = log(x, lns);
  1320.                     if (Double.isInfinite(lores)) { // don't allow this to be converted to NaN
  1321.                         return lores;
  1322.                     }

  1323.                     double lna = lns[0];
  1324.                     double lnb = lns[1];

  1325.                     /* resplit lns */
  1326.                     final double tmp1 = lna * HEX_40000000;
  1327.                     final double tmp2 = (lna + tmp1) - tmp1;
  1328.                     lnb += lna - tmp2;
  1329.                     lna = tmp2;

  1330.                     // y*ln(x) = (aa+ab)
  1331.                     final double aa = lna * ya;
  1332.                     final double ab = lna * yb + lnb * ya + lnb * yb;

  1333.                     lna = aa + ab;
  1334.                     lnb = -(lna - aa - ab);

  1335.                     double z = 1.0 / 120.0;
  1336.                     z = z * lnb + (1.0 / 24.0);
  1337.                     z = z * lnb + (1.0 / 6.0);
  1338.                     z = z * lnb + 0.5;
  1339.                     z = z * lnb + 1.0;
  1340.                     z *= lnb;

  1341.                     final double result = exp(lna, z, null);
  1342.                     //result = result + result * z;
  1343.                     return result;
  1344.                 }
  1345.             }
  1346.         }
  1347.     }

  1348.     /**
  1349.      * Raise a double to an int power.
  1350.      *
  1351.      * @param d Number to raise.
  1352.      * @param e Exponent.
  1353.      * @return d<sup>e</sup>
  1354.      * @since 3.1
  1355.      */
  1356.     public static double pow(double d, int e) {
  1357.         return pow(d, (long) e);
  1358.     }


  1359.     /**
  1360.      * Raise a double to a long power.
  1361.      *
  1362.      * @param d Number to raise.
  1363.      * @param e Exponent.
  1364.      * @return d<sup>e</sup>
  1365.      * @since 3.6
  1366.      */
  1367.     public static double pow(double d, long e) {
  1368.         if (e == 0) {
  1369.             return 1.0;
  1370.         } else if (e > 0) {
  1371.             return new Split(d).pow(e).full;
  1372.         } else {
  1373.             return new Split(d).reciprocal().pow(-e).full;
  1374.         }
  1375.     }

  1376.     /** Class operator on double numbers split into one 26 bits number and one 27 bits number. */
  1377.     private static class Split {

  1378.         /** Split version of NaN. */
  1379.         public static final Split NAN = new Split(Double.NaN, 0);

  1380.         /** Split version of positive infinity. */
  1381.         public static final Split POSITIVE_INFINITY = new Split(Double.POSITIVE_INFINITY, 0);

  1382.         /** Split version of negative infinity. */
  1383.         public static final Split NEGATIVE_INFINITY = new Split(Double.NEGATIVE_INFINITY, 0);

  1384.         /** Full number. */
  1385.         private final double full;

  1386.         /** High order bits. */
  1387.         private final double high;

  1388.         /** Low order bits. */
  1389.         private final double low;

  1390.         /** Simple constructor.
  1391.          * @param x number to split
  1392.          */
  1393.         Split(final double x) {
  1394.             full = x;
  1395.             high = Double.longBitsToDouble(Double.doubleToRawLongBits(x) & ((-1L) << 27));
  1396.             low  = x - high;
  1397.         }

  1398.         /** Simple constructor.
  1399.          * @param high high order bits
  1400.          * @param low low order bits
  1401.          */
  1402.         Split(final double high, final double low) {
  1403.             this(high == 0.0 ? (low == 0.0 && Double.doubleToRawLongBits(high) == Long.MIN_VALUE /* negative zero */ ? -0.0 : low) : high + low, high, low);
  1404.         }

  1405.         /** Simple constructor.
  1406.          * @param full full number
  1407.          * @param high high order bits
  1408.          * @param low low order bits
  1409.          */
  1410.         Split(final double full, final double high, final double low) {
  1411.             this.full = full;
  1412.             this.high = high;
  1413.             this.low  = low;
  1414.         }

  1415.         /** Multiply the instance by another one.
  1416.          * @param b other instance to multiply by
  1417.          * @return product
  1418.          */
  1419.         public Split multiply(final Split b) {
  1420.             // beware the following expressions must NOT be simplified, they rely on floating point arithmetic properties
  1421.             final Split  mulBasic  = new Split(full * b.full);
  1422.             final double mulError  = low * b.low - (((mulBasic.full - high * b.high) - low * b.high) - high * b.low);
  1423.             return new Split(mulBasic.high, mulBasic.low + mulError);
  1424.         }

  1425.         /** Compute the reciprocal of the instance.
  1426.          * @return reciprocal of the instance
  1427.          */
  1428.         public Split reciprocal() {

  1429.             final double approximateInv = 1.0 / full;
  1430.             final Split  splitInv       = new Split(approximateInv);

  1431.             // if 1.0/d were computed perfectly, remultiplying it by d should give 1.0
  1432.             // we want to estimate the error so we can fix the low order bits of approximateInvLow
  1433.             // beware the following expressions must NOT be simplified, they rely on floating point arithmetic properties
  1434.             final Split product = multiply(splitInv);
  1435.             final double error  = (product.high - 1) + product.low;

  1436.             // better accuracy estimate of reciprocal
  1437.             return Double.isNaN(error) ? splitInv : new Split(splitInv.high, splitInv.low - error / full);
  1438.         }

  1439.         /** Computes this^e.
  1440.          * @param e exponent (beware, here it MUST be > 0; the only exclusion is Long.MIN_VALUE)
  1441.          * @return d^e, split in high and low bits
  1442.          * @since 3.6
  1443.          */
  1444.         private Split pow(final long e) {

  1445.             // prepare result
  1446.             Split result = new Split(1);

  1447.             // d^(2p)
  1448.             Split d2p = new Split(full, high, low);

  1449.             for (long p = e; p != 0; p >>>= 1) {

  1450.                 if ((p & 0x1) != 0) {
  1451.                     // accurate multiplication result = result * d^(2p) using Veltkamp TwoProduct algorithm
  1452.                     result = result.multiply(d2p);
  1453.                 }

  1454.                 // accurate squaring d^(2(p+1)) = d^(2p) * d^(2p) using Veltkamp TwoProduct algorithm
  1455.                 d2p = d2p.multiply(d2p);
  1456.             }

  1457.             if (Double.isNaN(result.full)) {
  1458.                 if (Double.isNaN(full)) {
  1459.                     return Split.NAN;
  1460.                 } else {
  1461.                     // some intermediate numbers exceeded capacity,
  1462.                     // and the low order bits became NaN (because infinity - infinity = NaN)
  1463.                     if (AccurateMath.abs(full) < 1) {
  1464.                         return new Split(AccurateMath.copySign(0.0, full), 0.0);
  1465.                     } else if (full < 0 && (e & 0x1) == 1) {
  1466.                         return Split.NEGATIVE_INFINITY;
  1467.                     } else {
  1468.                         return Split.POSITIVE_INFINITY;
  1469.                     }
  1470.                 }
  1471.             } else {
  1472.                 return result;
  1473.             }
  1474.         }
  1475.     }

  1476.     /**
  1477.      *  Computes sin(x) - x, where |x| < 1/16.
  1478.      *  Use a Remez polynomial approximation.
  1479.      *  @param x a number smaller than 1/16
  1480.      *  @return sin(x) - x
  1481.      */
  1482.     private static double polySine(final double x) {
  1483.         double x2 = x * x;

  1484.         double p = 2.7553817452272217E-6;
  1485.         p = p * x2 + -1.9841269659586505E-4;
  1486.         p = p * x2 + 0.008333333333329196;
  1487.         p = p * x2 + -0.16666666666666666;
  1488.         //p *= x2;
  1489.         //p *= x;
  1490.         p = p * x2 * x;

  1491.         return p;
  1492.     }

  1493.     /**
  1494.      *  Computes cos(x) - 1, where |x| < 1/16.
  1495.      *  Use a Remez polynomial approximation.
  1496.      *  @param x a number smaller than 1/16
  1497.      *  @return cos(x) - 1
  1498.      */
  1499.     private static double polyCosine(double x) {
  1500.         double x2 = x * x;

  1501.         double p = 2.479773539153719E-5;
  1502.         p = p * x2 + -0.0013888888689039883;
  1503.         p = p * x2 + 0.041666666666621166;
  1504.         p = p * x2 + -0.49999999999999994;
  1505.         p *= x2;

  1506.         return p;
  1507.     }

  1508.     /**
  1509.      *  Compute sine over the first quadrant (0 < x < pi/2).
  1510.      *  Use combination of table lookup and rational polynomial expansion.
  1511.      *  @param xa number from which sine is requested
  1512.      *  @param xb extra bits for x (may be 0.0)
  1513.      *  @return sin(xa + xb)
  1514.      */
  1515.     private static double sinQ(double xa, double xb) {
  1516.         int idx = (int) ((xa * 8.0) + 0.5);
  1517.         final double epsilon = xa - EIGHTHS[idx]; //idx*0.125;

  1518.         // Table lookups
  1519.         final double sintA = SINE_TABLE_A[idx];
  1520.         final double sintB = SINE_TABLE_B[idx];
  1521.         final double costA = COSINE_TABLE_A[idx];
  1522.         final double costB = COSINE_TABLE_B[idx];

  1523.         // Polynomial eval of sin(epsilon), cos(epsilon)
  1524.         double sinEpsA = epsilon;
  1525.         double sinEpsB = polySine(epsilon);
  1526.         final double cosEpsA = 1.0;
  1527.         final double cosEpsB = polyCosine(epsilon);

  1528.         // Split epsilon   xa + xb = x
  1529.         final double temp = sinEpsA * HEX_40000000;
  1530.         double temp2 = (sinEpsA + temp) - temp;
  1531.         sinEpsB +=  sinEpsA - temp2;
  1532.         sinEpsA = temp2;

  1533.         /* Compute sin(x) by angle addition formula */
  1534.         double result;

  1535.         /* Compute the following sum:
  1536.          *
  1537.          * result = sintA + costA*sinEpsA + sintA*cosEpsB + costA*sinEpsB +
  1538.          *          sintB + costB*sinEpsA + sintB*cosEpsB + costB*sinEpsB;
  1539.          *
  1540.          * Ranges of elements
  1541.          *
  1542.          * xxxtA   0            PI/2
  1543.          * xxxtB   -1.5e-9      1.5e-9
  1544.          * sinEpsA -0.0625      0.0625
  1545.          * sinEpsB -6e-11       6e-11
  1546.          * cosEpsA  1.0
  1547.          * cosEpsB  0           -0.0625
  1548.          *
  1549.          */

  1550.         //result = sintA + costA*sinEpsA + sintA*cosEpsB + costA*sinEpsB +
  1551.         //          sintB + costB*sinEpsA + sintB*cosEpsB + costB*sinEpsB;

  1552.         //result = sintA + sintA*cosEpsB + sintB + sintB * cosEpsB;
  1553.         //result += costA*sinEpsA + costA*sinEpsB + costB*sinEpsA + costB * sinEpsB;
  1554.         double a = 0;
  1555.         double b = 0;

  1556.         double t = sintA;
  1557.         double c = a + t;
  1558.         double d = -(c - a - t);
  1559.         a = c;
  1560.         b += d;

  1561.         t = costA * sinEpsA;
  1562.         c = a + t;
  1563.         d = -(c - a - t);
  1564.         a = c;
  1565.         b += d;

  1566.         b = b + sintA * cosEpsB + costA * sinEpsB;
  1567.         /*
  1568.         t = sintA*cosEpsB;
  1569.         c = a + t;
  1570.         d = -(c - a - t);
  1571.         a = c;
  1572.         b = b + d;

  1573.         t = costA*sinEpsB;
  1574.         c = a + t;
  1575.         d = -(c - a - t);
  1576.         a = c;
  1577.         b = b + d;
  1578.          */

  1579.         b = b + sintB + costB * sinEpsA + sintB * cosEpsB + costB * sinEpsB;
  1580.         /*
  1581.         t = sintB;
  1582.         c = a + t;
  1583.         d = -(c - a - t);
  1584.         a = c;
  1585.         b = b + d;

  1586.         t = costB*sinEpsA;
  1587.         c = a + t;
  1588.         d = -(c - a - t);
  1589.         a = c;
  1590.         b = b + d;

  1591.         t = sintB*cosEpsB;
  1592.         c = a + t;
  1593.         d = -(c - a - t);
  1594.         a = c;
  1595.         b = b + d;

  1596.         t = costB*sinEpsB;
  1597.         c = a + t;
  1598.         d = -(c - a - t);
  1599.         a = c;
  1600.         b = b + d;
  1601.          */

  1602.         if (xb != 0.0) {
  1603.             t = ((costA + costB) * (cosEpsA + cosEpsB) -
  1604.                  (sintA + sintB) * (sinEpsA + sinEpsB)) * xb;  // approximate cosine*xb
  1605.             c = a + t;
  1606.             d = -(c - a - t);
  1607.             a = c;
  1608.             b += d;
  1609.         }

  1610.         result = a + b;

  1611.         return result;
  1612.     }

  1613.     /**
  1614.      * Compute cosine in the first quadrant by subtracting input from PI/2 and
  1615.      * then calling sinQ.  This is more accurate as the input approaches PI/2.
  1616.      *  @param xa number from which cosine is requested
  1617.      *  @param xb extra bits for x (may be 0.0)
  1618.      *  @return cos(xa + xb)
  1619.      */
  1620.     private static double cosQ(double xa, double xb) {
  1621.         final double pi2a = 1.5707963267948966;
  1622.         final double pi2b = 6.123233995736766E-17;

  1623.         final double a = pi2a - xa;
  1624.         double b = -(a - pi2a + xa);
  1625.         b += pi2b - xb;

  1626.         return sinQ(a, b);
  1627.     }

  1628.     /**
  1629.      *  Compute tangent (or cotangent) over the first quadrant.   0 < x < pi/2
  1630.      *  Use combination of table lookup and rational polynomial expansion.
  1631.      *  @param xa number from which sine is requested
  1632.      *  @param xb extra bits for x (may be 0.0)
  1633.      *  @param cotanFlag if true, compute the cotangent instead of the tangent
  1634.      *  @return tan(xa+xb) (or cotangent, depending on cotanFlag)
  1635.      */
  1636.     private static double tanQ(double xa, double xb, boolean cotanFlag) {

  1637.         int idx = (int) ((xa * 8.0) + 0.5);
  1638.         final double epsilon = xa - EIGHTHS[idx]; //idx*0.125;

  1639.         // Table lookups
  1640.         final double sintA = SINE_TABLE_A[idx];
  1641.         final double sintB = SINE_TABLE_B[idx];
  1642.         final double costA = COSINE_TABLE_A[idx];
  1643.         final double costB = COSINE_TABLE_B[idx];

  1644.         // Polynomial eval of sin(epsilon), cos(epsilon)
  1645.         double sinEpsA = epsilon;
  1646.         double sinEpsB = polySine(epsilon);
  1647.         final double cosEpsA = 1.0;
  1648.         final double cosEpsB = polyCosine(epsilon);

  1649.         // Split epsilon   xa + xb = x
  1650.         double temp = sinEpsA * HEX_40000000;
  1651.         double temp2 = (sinEpsA + temp) - temp;
  1652.         sinEpsB +=  sinEpsA - temp2;
  1653.         sinEpsA = temp2;

  1654.         /* Compute sin(x) by angle addition formula */

  1655.         /* Compute the following sum:
  1656.          *
  1657.          * result = sintA + costA*sinEpsA + sintA*cosEpsB + costA*sinEpsB +
  1658.          *          sintB + costB*sinEpsA + sintB*cosEpsB + costB*sinEpsB;
  1659.          *
  1660.          * Ranges of elements
  1661.          *
  1662.          * xxxtA   0            PI/2
  1663.          * xxxtB   -1.5e-9      1.5e-9
  1664.          * sinEpsA -0.0625      0.0625
  1665.          * sinEpsB -6e-11       6e-11
  1666.          * cosEpsA  1.0
  1667.          * cosEpsB  0           -0.0625
  1668.          *
  1669.          */

  1670.         //result = sintA + costA*sinEpsA + sintA*cosEpsB + costA*sinEpsB +
  1671.         //          sintB + costB*sinEpsA + sintB*cosEpsB + costB*sinEpsB;

  1672.         //result = sintA + sintA*cosEpsB + sintB + sintB * cosEpsB;
  1673.         //result += costA*sinEpsA + costA*sinEpsB + costB*sinEpsA + costB * sinEpsB;
  1674.         double a = 0;
  1675.         double b = 0;

  1676.         // Compute sine
  1677.         double t = sintA;
  1678.         double c = a + t;
  1679.         double d = -(c - a - t);
  1680.         a = c;
  1681.         b += d;

  1682.         t = costA * sinEpsA;
  1683.         c = a + t;
  1684.         d = -(c - a - t);
  1685.         a = c;
  1686.         b += d;

  1687.         b += sintA * cosEpsB + costA * sinEpsB;
  1688.         b += sintB + costB * sinEpsA + sintB * cosEpsB + costB * sinEpsB;

  1689.         double sina = a + b;
  1690.         double sinb = -(sina - a - b);

  1691.         // Compute cosine

  1692.         a = b = c = d = 0.0;

  1693.         t = costA * cosEpsA;
  1694.         c = a + t;
  1695.         d = -(c - a - t);
  1696.         a = c;
  1697.         b += d;

  1698.         t = -sintA * sinEpsA;
  1699.         c = a + t;
  1700.         d = -(c - a - t);
  1701.         a = c;
  1702.         b += d;

  1703.         b += costB * cosEpsA + costA * cosEpsB + costB * cosEpsB;
  1704.         b -= sintB * sinEpsA + sintA * sinEpsB + sintB * sinEpsB;

  1705.         double cosa = a + b;
  1706.         double cosb = -(cosa - a - b);

  1707.         if (cotanFlag) {
  1708.             double tmp;
  1709.             tmp = cosa; cosa = sina; sina = tmp;
  1710.             tmp = cosb; cosb = sinb; sinb = tmp;
  1711.         }


  1712.         /* estimate and correct, compute 1.0/(cosa+cosb) */
  1713.         /*
  1714.     double est = (sina+sinb)/(cosa+cosb);
  1715.     double err = (sina - cosa*est) + (sinb - cosb*est);
  1716.     est += err/(cosa+cosb);
  1717.     err = (sina - cosa*est) + (sinb - cosb*est);
  1718.          */

  1719.         // f(x) = 1/x,   f'(x) = -1/x^2

  1720.         double est = sina / cosa;

  1721.         /* Split the estimate to get more accurate read on division rounding */
  1722.         temp = est * HEX_40000000;
  1723.         double esta = (est + temp) - temp;
  1724.         double estb =  est - esta;

  1725.         temp = cosa * HEX_40000000;
  1726.         double cosaa = (cosa + temp) - temp;
  1727.         double cosab =  cosa - cosaa;

  1728.         //double err = (sina - est*cosa)/cosa;  // Correction for division rounding
  1729.         double err = (sina - esta * cosaa - esta * cosab - estb * cosaa - estb * cosab) / cosa;  // Correction for division rounding
  1730.         err += sinb / cosa;                   // Change in est due to sinb
  1731.         err += -sina * cosb / cosa / cosa;    // Change in est due to cosb

  1732.         if (xb != 0.0) {
  1733.             // tan' = 1 + tan^2      cot' = -(1 + cot^2)
  1734.             // Approximate impact of xb
  1735.             double xbadj = xb + est * est * xb;
  1736.             if (cotanFlag) {
  1737.                 xbadj = -xbadj;
  1738.             }

  1739.             err += xbadj;
  1740.         }

  1741.         return est + err;
  1742.     }

  1743.     /** Reduce the input argument using the Payne and Hanek method.
  1744.      *  This is good for all inputs 0.0 < x < inf
  1745.      *  Output is remainder after dividing by PI/2
  1746.      *  The result array should contain 3 numbers.
  1747.      *  result[0] is the integer portion, so mod 4 this gives the quadrant.
  1748.      *  result[1] is the upper bits of the remainder
  1749.      *  result[2] is the lower bits of the remainder
  1750.      *
  1751.      * @param x number to reduce
  1752.      * @param result placeholder where to put the result
  1753.      */
  1754.     private static void reducePayneHanek(double x, double[] result) {
  1755.         /* Convert input double to bits */
  1756.         long inbits = Double.doubleToRawLongBits(x);
  1757.         int exponent = (int) ((inbits >> 52) & 0x7ff) - 1023;

  1758.         /* Convert to fixed point representation */
  1759.         inbits &= 0x000fffffffffffffL;
  1760.         inbits |= 0x0010000000000000L;

  1761.         /* Normalize input to be between 0.5 and 1.0 */
  1762.         exponent++;
  1763.         inbits <<= 11;

  1764.         /* Based on the exponent, get a shifted copy of recip2pi */
  1765.         long shpi0;
  1766.         long shpiA;
  1767.         long shpiB;
  1768.         int idx = exponent >> 6;
  1769.         int shift = exponent - (idx << 6);

  1770.         if (shift != 0) {
  1771.             shpi0 = (idx == 0) ? 0 : (RECIP_2PI[idx - 1] << shift);
  1772.             shpi0 |= RECIP_2PI[idx] >>> (64 - shift);
  1773.             shpiA = (RECIP_2PI[idx] << shift) | (RECIP_2PI[idx + 1] >>> (64 - shift));
  1774.             shpiB = (RECIP_2PI[idx + 1] << shift) | (RECIP_2PI[idx + 2] >>> (64 - shift));
  1775.         } else {
  1776.             shpi0 = (idx == 0) ? 0 : RECIP_2PI[idx - 1];
  1777.             shpiA = RECIP_2PI[idx];
  1778.             shpiB = RECIP_2PI[idx + 1];
  1779.         }

  1780.         /* Multiply input by shpiA */
  1781.         long a = inbits >>> 32;
  1782.         long b = inbits & 0xffffffffL;

  1783.         long c = shpiA >>> 32;
  1784.         long d = shpiA & 0xffffffffL;

  1785.         long ac = a * c;
  1786.         long bd = b * d;
  1787.         long bc = b * c;
  1788.         long ad = a * d;

  1789.         long prodB = bd + (ad << 32);
  1790.         long prodA = ac + (ad >>> 32);

  1791.         boolean bita = (bd & 0x8000000000000000L) != 0;
  1792.         boolean bitb = (ad & 0x80000000L) != 0;
  1793.         boolean bitsum = (prodB & 0x8000000000000000L) != 0;

  1794.         /* Carry */
  1795.         if ((bita && bitb) ||
  1796.                 ((bita || bitb) && !bitsum)) {
  1797.             prodA++;
  1798.         }

  1799.         bita = (prodB & 0x8000000000000000L) != 0;
  1800.         bitb = (bc & 0x80000000L) != 0;

  1801.         prodB += bc << 32;
  1802.         prodA += bc >>> 32;

  1803.         bitsum = (prodB & 0x8000000000000000L) != 0;

  1804.         /* Carry */
  1805.         if ((bita && bitb) ||
  1806.                 ((bita || bitb) && !bitsum)) {
  1807.             prodA++;
  1808.         }

  1809.         /* Multiply input by shpiB */
  1810.         c = shpiB >>> 32;
  1811.         d = shpiB & 0xffffffffL;
  1812.         ac = a * c;
  1813.         bc = b * c;
  1814.         ad = a * d;

  1815.         /* Collect terms */
  1816.         ac += (bc + ad) >>> 32;

  1817.         bita = (prodB & 0x8000000000000000L) != 0;
  1818.         bitb = (ac & 0x8000000000000000L) != 0;
  1819.         prodB += ac;
  1820.         bitsum = (prodB & 0x8000000000000000L) != 0;
  1821.         /* Carry */
  1822.         if ((bita && bitb) ||
  1823.                 ((bita || bitb) && !bitsum)) {
  1824.             prodA++;
  1825.         }

  1826.         /* Multiply by shpi0 */
  1827.         c = shpi0 >>> 32;
  1828.         d = shpi0 & 0xffffffffL;

  1829.         bd = b * d;
  1830.         bc = b * c;
  1831.         ad = a * d;

  1832.         prodA += bd + ((bc + ad) << 32);

  1833.         /*
  1834.          * prodA, prodB now contain the remainder as a fraction of PI.  We want this as a fraction of
  1835.          * PI/2, so use the following steps:
  1836.          * 1.) multiply by 4.
  1837.          * 2.) do a fixed point muliply by PI/4.
  1838.          * 3.) Convert to floating point.
  1839.          * 4.) Multiply by 2
  1840.          */

  1841.         /* This identifies the quadrant */
  1842.         int intPart = (int)(prodA >>> 62);

  1843.         /* Multiply by 4 */
  1844.         prodA <<= 2;
  1845.         prodA |= prodB >>> 62;
  1846.         prodB <<= 2;

  1847.         /* Multiply by PI/4 */
  1848.         a = prodA >>> 32;
  1849.         b = prodA & 0xffffffffL;

  1850.         c = PI_O_4_BITS[0] >>> 32;
  1851.         d = PI_O_4_BITS[0] & 0xffffffffL;

  1852.         ac = a * c;
  1853.         bd = b * d;
  1854.         bc = b * c;
  1855.         ad = a * d;

  1856.         long prod2B = bd + (ad << 32);
  1857.         long prod2A = ac + (ad >>> 32);

  1858.         bita = (bd & 0x8000000000000000L) != 0;
  1859.         bitb = (ad & 0x80000000L) != 0;
  1860.         bitsum = (prod2B & 0x8000000000000000L) != 0;

  1861.         /* Carry */
  1862.         if ((bita && bitb) ||
  1863.                 ((bita || bitb) && !bitsum)) {
  1864.             prod2A++;
  1865.         }

  1866.         bita = (prod2B & 0x8000000000000000L) != 0;
  1867.         bitb = (bc & 0x80000000L) != 0;

  1868.         prod2B += bc << 32;
  1869.         prod2A += bc >>> 32;

  1870.         bitsum = (prod2B & 0x8000000000000000L) != 0;

  1871.         /* Carry */
  1872.         if ((bita && bitb) ||
  1873.                 ((bita || bitb) && !bitsum)) {
  1874.             prod2A++;
  1875.         }

  1876.         /* Multiply input by pio4bits[1] */
  1877.         c = PI_O_4_BITS[1] >>> 32;
  1878.         d = PI_O_4_BITS[1] & 0xffffffffL;
  1879.         ac = a * c;
  1880.         bc = b * c;
  1881.         ad = a * d;

  1882.         /* Collect terms */
  1883.         ac += (bc + ad) >>> 32;

  1884.         bita = (prod2B & 0x8000000000000000L) != 0;
  1885.         bitb = (ac & 0x8000000000000000L) != 0;
  1886.         prod2B += ac;
  1887.         bitsum = (prod2B & 0x8000000000000000L) != 0;
  1888.         /* Carry */
  1889.         if ((bita && bitb) ||
  1890.                 ((bita || bitb) && !bitsum)) {
  1891.             prod2A++;
  1892.         }

  1893.         /* Multiply inputB by pio4bits[0] */
  1894.         a = prodB >>> 32;
  1895.         b = prodB & 0xffffffffL;
  1896.         c = PI_O_4_BITS[0] >>> 32;
  1897.         d = PI_O_4_BITS[0] & 0xffffffffL;
  1898.         ac = a * c;
  1899.         bc = b * c;
  1900.         ad = a * d;

  1901.         /* Collect terms */
  1902.         ac += (bc + ad) >>> 32;

  1903.         bita = (prod2B & 0x8000000000000000L) != 0;
  1904.         bitb = (ac & 0x8000000000000000L) != 0;
  1905.         prod2B += ac;
  1906.         bitsum = (prod2B & 0x8000000000000000L) != 0;
  1907.         /* Carry */
  1908.         if ((bita && bitb) ||
  1909.                 ((bita || bitb) && !bitsum)) {
  1910.             prod2A++;
  1911.         }

  1912.         /* Convert to double */
  1913.         double tmpA = (prod2A >>> 12) / TWO_POWER_52;  // High order 52 bits
  1914.         double tmpB = (((prod2A & 0xfffL) << 40) + (prod2B >>> 24)) / TWO_POWER_52 / TWO_POWER_52; // Low bits

  1915.         double sumA = tmpA + tmpB;
  1916.         double sumB = -(sumA - tmpA - tmpB);

  1917.         /* Multiply by PI/2 and return */
  1918.         result[0] = intPart;
  1919.         result[1] = sumA * 2.0;
  1920.         result[2] = sumB * 2.0;
  1921.     }

  1922.     /**
  1923.      * Sine function.
  1924.      *
  1925.      * @param x Argument.
  1926.      * @return sin(x)
  1927.      */
  1928.     public static double sin(double x) {
  1929.         boolean negative = false;
  1930.         int quadrant = 0;
  1931.         double xa;
  1932.         double xb = 0.0;

  1933.         /* Take absolute value of the input */
  1934.         xa = x;
  1935.         if (x < 0) {
  1936.             negative = true;
  1937.             xa = -xa;
  1938.         }

  1939.         /* Check for zero and negative zero */
  1940.         if (xa == 0.0) {
  1941.             long bits = Double.doubleToRawLongBits(x);
  1942.             if (bits < 0) {
  1943.                 return -0.0;
  1944.             }
  1945.             return 0.0;
  1946.         }

  1947.         if (xa != xa || xa == Double.POSITIVE_INFINITY) {
  1948.             return Double.NaN;
  1949.         }

  1950.         /* Perform any argument reduction */
  1951.         if (xa > 3294198.0) {
  1952.             // PI * (2**20)
  1953.             // Argument too big for CodyWaite reduction.  Must use
  1954.             // PayneHanek.
  1955.             double[] reduceResults = new double[3];
  1956.             reducePayneHanek(xa, reduceResults);
  1957.             quadrant = ((int) reduceResults[0]) & 3;
  1958.             xa = reduceResults[1];
  1959.             xb = reduceResults[2];
  1960.         } else if (xa > 1.5707963267948966) {
  1961.             final CodyWaite cw = new CodyWaite(xa);
  1962.             quadrant = cw.getK() & 3;
  1963.             xa = cw.getRemA();
  1964.             xb = cw.getRemB();
  1965.         }

  1966.         if (negative) {
  1967.             quadrant ^= 2;  // Flip bit 1
  1968.         }

  1969.         switch (quadrant) {
  1970.         case 0:
  1971.             return sinQ(xa, xb);
  1972.         case 1:
  1973.             return cosQ(xa, xb);
  1974.         case 2:
  1975.             return -sinQ(xa, xb);
  1976.         case 3:
  1977.             return -cosQ(xa, xb);
  1978.         default:
  1979.             return Double.NaN;
  1980.         }
  1981.     }

  1982.     /**
  1983.      * Cosine function.
  1984.      *
  1985.      * @param x Argument.
  1986.      * @return cos(x)
  1987.      */
  1988.     public static double cos(double x) {
  1989.         int quadrant = 0;

  1990.         /* Take absolute value of the input */
  1991.         double xa = x;
  1992.         if (x < 0) {
  1993.             xa = -xa;
  1994.         }

  1995.         if (xa != xa || xa == Double.POSITIVE_INFINITY) {
  1996.             return Double.NaN;
  1997.         }

  1998.         /* Perform any argument reduction */
  1999.         double xb = 0;
  2000.         if (xa > 3294198.0) {
  2001.             // PI * (2**20)
  2002.             // Argument too big for CodyWaite reduction.  Must use
  2003.             // PayneHanek.
  2004.             double[] reduceResults = new double[3];
  2005.             reducePayneHanek(xa, reduceResults);
  2006.             quadrant = ((int) reduceResults[0]) & 3;
  2007.             xa = reduceResults[1];
  2008.             xb = reduceResults[2];
  2009.         } else if (xa > 1.5707963267948966) {
  2010.             final CodyWaite cw = new CodyWaite(xa);
  2011.             quadrant = cw.getK() & 3;
  2012.             xa = cw.getRemA();
  2013.             xb = cw.getRemB();
  2014.         }

  2015.         //if (negative)
  2016.         //  quadrant = (quadrant + 2) % 4;

  2017.         switch (quadrant) {
  2018.         case 0:
  2019.             return cosQ(xa, xb);
  2020.         case 1:
  2021.             return -sinQ(xa, xb);
  2022.         case 2:
  2023.             return -cosQ(xa, xb);
  2024.         case 3:
  2025.             return sinQ(xa, xb);
  2026.         default:
  2027.             return Double.NaN;
  2028.         }
  2029.     }

  2030.     /**
  2031.      * Tangent function.
  2032.      *
  2033.      * @param x Argument.
  2034.      * @return tan(x)
  2035.      */
  2036.     public static double tan(double x) {
  2037.         boolean negative = false;
  2038.         int quadrant = 0;

  2039.         /* Take absolute value of the input */
  2040.         double xa = x;
  2041.         if (x < 0) {
  2042.             negative = true;
  2043.             xa = -xa;
  2044.         }

  2045.         /* Check for zero and negative zero */
  2046.         if (xa == 0.0) {
  2047.             long bits = Double.doubleToRawLongBits(x);
  2048.             if (bits < 0) {
  2049.                 return -0.0;
  2050.             }
  2051.             return 0.0;
  2052.         }

  2053.         if (xa != xa || xa == Double.POSITIVE_INFINITY) {
  2054.             return Double.NaN;
  2055.         }

  2056.         /* Perform any argument reduction */
  2057.         double xb = 0;
  2058.         if (xa > 3294198.0) {
  2059.             // PI * (2**20)
  2060.             // Argument too big for CodyWaite reduction.  Must use
  2061.             // PayneHanek.
  2062.             double[] reduceResults = new double[3];
  2063.             reducePayneHanek(xa, reduceResults);
  2064.             quadrant = ((int) reduceResults[0]) & 3;
  2065.             xa = reduceResults[1];
  2066.             xb = reduceResults[2];
  2067.         } else if (xa > 1.5707963267948966) {
  2068.             final CodyWaite cw = new CodyWaite(xa);
  2069.             quadrant = cw.getK() & 3;
  2070.             xa = cw.getRemA();
  2071.             xb = cw.getRemB();
  2072.         }

  2073.         if (xa > 1.5) {
  2074.             // Accuracy suffers between 1.5 and PI/2
  2075.             final double pi2a = 1.5707963267948966;
  2076.             final double pi2b = 6.123233995736766E-17;

  2077.             final double a = pi2a - xa;
  2078.             double b = -(a - pi2a + xa);
  2079.             b += pi2b - xb;

  2080.             xa = a + b;
  2081.             xb = -(xa - a - b);
  2082.             quadrant ^= 1;
  2083.             negative ^= true;
  2084.         }

  2085.         double result;
  2086.         if ((quadrant & 1) == 0) {
  2087.             result = tanQ(xa, xb, false);
  2088.         } else {
  2089.             result = -tanQ(xa, xb, true);
  2090.         }

  2091.         if (negative) {
  2092.             result = -result;
  2093.         }

  2094.         return result;
  2095.     }

  2096.     /**
  2097.      * Arctangent function.
  2098.      *  @param x a number
  2099.      *  @return atan(x)
  2100.      */
  2101.     public static double atan(double x) {
  2102.         return atan(x, 0.0, false);
  2103.     }

  2104.     /** Internal helper function to compute arctangent.
  2105.      * @param xa number from which arctangent is requested
  2106.      * @param xb extra bits for x (may be 0.0)
  2107.      * @param leftPlane if true, result angle must be put in the left half plane
  2108.      * @return atan(xa + xb) (or angle shifted by {@code PI} if leftPlane is true)
  2109.      */
  2110.     private static double atan(double xa, double xb, boolean leftPlane) {
  2111.         if (xa == 0.0) { // Matches +/- 0.0; return correct sign
  2112.             return leftPlane ? copySign(Math.PI, xa) : xa;
  2113.         }

  2114.         final boolean negate;
  2115.         if (xa < 0) {
  2116.             // negative
  2117.             xa = -xa;
  2118.             xb = -xb;
  2119.             negate = true;
  2120.         } else {
  2121.             negate = false;
  2122.         }

  2123.         if (xa > 1.633123935319537E16) { // Very large input
  2124.             return (negate ^ leftPlane) ? (-Math.PI * F_1_2) : (Math.PI * F_1_2);
  2125.         }

  2126.         /* Estimate the closest tabulated arctan value, compute eps = xa-tangentTable */
  2127.         final int idx;
  2128.         if (xa < 1) {
  2129.             idx = (int) (((-1.7168146928204136 * xa * xa + 8.0) * xa) + 0.5);
  2130.         } else {
  2131.             final double oneOverXa = 1 / xa;
  2132.             idx = (int) (-((-1.7168146928204136 * oneOverXa * oneOverXa + 8.0) * oneOverXa) + 13.07);
  2133.         }

  2134.         final double ttA = TANGENT_TABLE_A[idx];
  2135.         final double ttB = TANGENT_TABLE_B[idx];

  2136.         double epsA = xa - ttA;
  2137.         double epsB = -(epsA - xa + ttA);
  2138.         epsB += xb - ttB;

  2139.         double temp = epsA + epsB;
  2140.         epsB = -(temp - epsA - epsB);
  2141.         epsA = temp;

  2142.         /* Compute eps = eps / (1.0 + xa*tangent) */
  2143.         temp = xa * HEX_40000000;
  2144.         double ya = xa + temp - temp;
  2145.         double yb = xb + xa - ya;
  2146.         xa = ya;
  2147.         xb += yb;

  2148.         //if (idx > 8 || idx == 0)
  2149.         if (idx == 0) {
  2150.             /* If the slope of the arctan is gentle enough (< 0.45), this approximation will suffice */
  2151.             //double denom = 1.0 / (1.0 + xa*tangentTableA[idx] + xb*tangentTableA[idx] + xa*tangentTableB[idx] + xb*tangentTableB[idx]);
  2152.             final double denom = 1d / (1d + (xa + xb) * (ttA + ttB));
  2153.             //double denom = 1.0 / (1.0 + xa*tangentTableA[idx]);
  2154.             ya = epsA * denom;
  2155.             yb = epsB * denom;
  2156.         } else {
  2157.             double temp2 = xa * ttA;
  2158.             double za = 1d + temp2;
  2159.             double zb = -(za - 1d - temp2);
  2160.             temp2 = xb * ttA + xa * ttB;
  2161.             temp = za + temp2;
  2162.             zb += -(temp - za - temp2);
  2163.             za = temp;

  2164.             zb += xb * ttB;
  2165.             ya = epsA / za;

  2166.             temp = ya * HEX_40000000;
  2167.             final double yaa = (ya + temp) - temp;
  2168.             final double yab = ya - yaa;

  2169.             temp = za * HEX_40000000;
  2170.             final double zaa = (za + temp) - temp;
  2171.             final double zab = za - zaa;

  2172.             /* Correct for rounding in division */
  2173.             yb = (epsA - yaa * zaa - yaa * zab - yab * zaa - yab * zab) / za;

  2174.             yb += -epsA * zb / za / za;
  2175.             yb += epsB / za;
  2176.         }


  2177.         epsA = ya;
  2178.         epsB = yb;

  2179.         /* Evaluate polynomial */
  2180.         final double epsA2 = epsA * epsA;

  2181.         /*
  2182.     yb = -0.09001346640161823;
  2183.     yb = yb * epsA2 + 0.11110718400605211;
  2184.     yb = yb * epsA2 + -0.1428571349122913;
  2185.     yb = yb * epsA2 + 0.19999999999273194;
  2186.     yb = yb * epsA2 + -0.33333333333333093;
  2187.     yb = yb * epsA2 * epsA;
  2188.          */

  2189.         yb = 0.07490822288864472;
  2190.         yb = yb * epsA2 - 0.09088450866185192;
  2191.         yb = yb * epsA2 + 0.11111095942313305;
  2192.         yb = yb * epsA2 - 0.1428571423679182;
  2193.         yb = yb * epsA2 + 0.19999999999923582;
  2194.         yb = yb * epsA2 - 0.33333333333333287;
  2195.         yb = yb * epsA2 * epsA;


  2196.         ya = epsA;

  2197.         temp = ya + yb;
  2198.         yb = -(temp - ya - yb);
  2199.         ya = temp;

  2200.         /* Add in effect of epsB.   atan'(x) = 1/(1+x^2) */
  2201.         yb += epsB / (1d + epsA * epsA);

  2202.         final double eighths = EIGHTHS[idx];

  2203.         //result = yb + eighths[idx] + ya;
  2204.         double za = eighths + ya;
  2205.         double zb = -(za - eighths - ya);
  2206.         temp = za + yb;
  2207.         zb += -(temp - za - yb);
  2208.         za = temp;

  2209.         double result = za + zb;

  2210.         if (leftPlane) {
  2211.             // Result is in the left plane
  2212.             final double resultb = -(result - za - zb);
  2213.             final double pia = 1.5707963267948966 * 2;
  2214.             final double pib = 6.123233995736766E-17 * 2;

  2215.             za = pia - result;
  2216.             zb = -(za - pia + result);
  2217.             zb += pib - resultb;

  2218.             result = za + zb;
  2219.         }


  2220.         if (negate ^ leftPlane) {
  2221.             result = -result;
  2222.         }

  2223.         return result;
  2224.     }

  2225.     /**
  2226.      * Two arguments arctangent function.
  2227.      * @param y ordinate
  2228.      * @param x abscissa
  2229.      * @return phase angle of point (x,y) between {@code -PI} and {@code PI}
  2230.      */
  2231.     public static double atan2(double y, double x) {
  2232.         if (Double.isNaN(x) || Double.isNaN(y)) {
  2233.             return Double.NaN;
  2234.         }

  2235.         if (y == 0) {
  2236.             final double invx = 1d / x;

  2237.             if (invx == 0) { // X is infinite
  2238.                 if (x > 0) {
  2239.                     return y; // return +/- 0.0
  2240.                 }
  2241.                 return copySign(Math.PI, y);
  2242.             }

  2243.             if (x < 0 || invx < 0) {
  2244.                 return copySign(Math.PI, y);
  2245.             }
  2246.             return x * y;
  2247.         }

  2248.         // y cannot now be zero

  2249.         if (y == Double.POSITIVE_INFINITY) {
  2250.             if (x == Double.POSITIVE_INFINITY) {
  2251.                 return Math.PI * F_1_4;
  2252.             }

  2253.             if (x == Double.NEGATIVE_INFINITY) {
  2254.                 return Math.PI * F_3_4;
  2255.             }

  2256.             return Math.PI * F_1_2;
  2257.         }

  2258.         if (y == Double.NEGATIVE_INFINITY) {
  2259.             if (x == Double.POSITIVE_INFINITY) {
  2260.                 return -Math.PI * F_1_4;
  2261.             }

  2262.             if (x == Double.NEGATIVE_INFINITY) {
  2263.                 return -Math.PI * F_3_4;
  2264.             }

  2265.             return -Math.PI * F_1_2;
  2266.         }

  2267.         if (x == Double.POSITIVE_INFINITY) {
  2268.             return y > 0 ? 0d : -0d;
  2269.         }

  2270.         if (x == Double.NEGATIVE_INFINITY) {
  2271.             return y > 0 ? Math.PI : -Math.PI;
  2272.         }

  2273.         // Neither y nor x can be infinite or NAN here

  2274.         if (x == 0) {
  2275.             return y > 0 ? Math.PI * F_1_2 : -Math.PI * F_1_2;
  2276.         }

  2277.         // Compute ratio r = y/x
  2278.         final double r = y / x;
  2279.         if (Double.isInfinite(r)) { // bypass calculations that can create NaN
  2280.             return atan(r, 0, x < 0);
  2281.         }

  2282.         double ra = doubleHighPart(r);
  2283.         double rb = r - ra;

  2284.         // Split x
  2285.         final double xa = doubleHighPart(x);
  2286.         final double xb = x - xa;

  2287.         rb += (y - ra * xa - ra * xb - rb * xa - rb * xb) / x;

  2288.         final double temp = ra + rb;
  2289.         rb = -(temp - ra - rb);
  2290.         ra = temp;

  2291.         if (ra == 0) { // Fix up the sign so atan works correctly
  2292.             ra = copySign(0d, y);
  2293.         }

  2294.         // Call atan
  2295.         return atan(ra, rb, x < 0);
  2296.     }

  2297.     /** Compute the arc sine of a number.
  2298.      * @param x number on which evaluation is done
  2299.      * @return arc sine of x
  2300.      */
  2301.     public static double asin(double x) {
  2302.         if (Double.isNaN(x)) {
  2303.             return Double.NaN;
  2304.         }

  2305.         if (x > 1.0 || x < -1.0) {
  2306.             return Double.NaN;
  2307.         }

  2308.         if (x == 1.0) {
  2309.             return Math.PI / 2.0;
  2310.         }

  2311.         if (x == -1.0) {
  2312.             return -Math.PI / 2.0;
  2313.         }

  2314.         if (x == 0.0) { // Matches +/- 0.0; return correct sign
  2315.             return x;
  2316.         }

  2317.         /* Compute asin(x) = atan(x/sqrt(1-x*x)) */

  2318.         /* Split x */
  2319.         double temp = x * HEX_40000000;
  2320.         final double xa = x + temp - temp;
  2321.         final double xb = x - xa;

  2322.         /* Square it */
  2323.         double ya = xa * xa;
  2324.         double yb = xa * xb * 2.0 + xb * xb;

  2325.         /* Subtract from 1 */
  2326.         ya = -ya;
  2327.         yb = -yb;

  2328.         double za = 1.0 + ya;
  2329.         double zb = -(za - 1.0 - ya);

  2330.         temp = za + yb;
  2331.         zb += -(temp - za - yb);
  2332.         za = temp;

  2333.         /* Square root */
  2334.         double y;
  2335.         y = Math.sqrt(za);
  2336.         temp = y * HEX_40000000;
  2337.         ya = y + temp - temp;
  2338.         yb = y - ya;

  2339.         /* Extend precision of sqrt */
  2340.         yb += (za - ya * ya - 2 * ya * yb - yb * yb) / (2.0 * y);

  2341.         /* Contribution of zb to sqrt */
  2342.         double dx = zb / (2.0 * y);

  2343.         // Compute ratio r = x/y
  2344.         double r = x / y;
  2345.         temp = r * HEX_40000000;
  2346.         double ra = r + temp - temp;
  2347.         double rb = r - ra;

  2348.         rb += (x - ra * ya - ra * yb - rb * ya - rb * yb) / y; // Correct for rounding in division
  2349.         rb += -x * dx / y / y; // Add in effect additional bits of sqrt.

  2350.         temp = ra + rb;
  2351.         rb = -(temp - ra - rb);
  2352.         ra = temp;

  2353.         return atan(ra, rb, false);
  2354.     }

  2355.     /** Compute the arc cosine of a number.
  2356.      * @param x number on which evaluation is done
  2357.      * @return arc cosine of x
  2358.      */
  2359.     public static double acos(double x) {
  2360.         if (Double.isNaN(x)) {
  2361.             return Double.NaN;
  2362.         }

  2363.         if (x > 1.0 || x < -1.0) {
  2364.             return Double.NaN;
  2365.         }

  2366.         if (x == -1.0) {
  2367.             return Math.PI;
  2368.         }

  2369.         if (x == 1.0) {
  2370.             return 0.0;
  2371.         }

  2372.         if (x == 0) {
  2373.             return Math.PI / 2.0;
  2374.         }

  2375.         /* Compute acos(x) = atan(sqrt(1-x*x)/x) */

  2376.         /* Split x */
  2377.         double temp = x * HEX_40000000;
  2378.         final double xa = x + temp - temp;
  2379.         final double xb = x - xa;

  2380.         /* Square it */
  2381.         double ya = xa * xa;
  2382.         double yb = xa * xb * 2.0 + xb * xb;

  2383.         /* Subtract from 1 */
  2384.         ya = -ya;
  2385.         yb = -yb;

  2386.         double za = 1.0 + ya;
  2387.         double zb = -(za - 1.0 - ya);

  2388.         temp = za + yb;
  2389.         zb += -(temp - za - yb);
  2390.         za = temp;

  2391.         /* Square root */
  2392.         double y = Math.sqrt(za);
  2393.         temp = y * HEX_40000000;
  2394.         ya = y + temp - temp;
  2395.         yb = y - ya;

  2396.         /* Extend precision of sqrt */
  2397.         yb += (za - ya * ya - 2 * ya * yb - yb * yb) / (2.0 * y);

  2398.         /* Contribution of zb to sqrt */
  2399.         yb += zb / (2.0 * y);
  2400.         y = ya + yb;
  2401.         yb = -(y - ya - yb);

  2402.         // Compute ratio r = y/x
  2403.         double r = y / x;

  2404.         // Did r overflow?
  2405.         if (Double.isInfinite(r)) { // x is effectively zero
  2406.             return Math.PI / 2; // so return the appropriate value
  2407.         }

  2408.         double ra = doubleHighPart(r);
  2409.         double rb = r - ra;

  2410.         rb += (y - ra * xa - ra * xb - rb * xa - rb * xb) / x; // Correct for rounding in division
  2411.         rb += yb / x; // Add in effect additional bits of sqrt.

  2412.         temp = ra + rb;
  2413.         rb = -(temp - ra - rb);
  2414.         ra = temp;

  2415.         return atan(ra, rb, x < 0);
  2416.     }

  2417.     /** Compute the cubic root of a number.
  2418.      * @param x number on which evaluation is done
  2419.      * @return cubic root of x
  2420.      */
  2421.     public static double cbrt(double x) {
  2422.         /* Convert input double to bits */
  2423.         long inbits = Double.doubleToRawLongBits(x);
  2424.         int exponent = (int) ((inbits >> 52) & 0x7ff) - 1023;
  2425.         boolean subnormal = false;

  2426.         if (exponent == -1023) {
  2427.             if (x == 0) {
  2428.                 return x;
  2429.             }

  2430.             /* Subnormal, so normalize */
  2431.             subnormal = true;
  2432.             x *= 1.8014398509481984E16; // 2^54
  2433.             inbits = Double.doubleToRawLongBits(x);
  2434.             exponent = (int) ((inbits >> 52) & 0x7ff) - 1023;
  2435.         }

  2436.         if (exponent == 1024) {
  2437.             // Nan or infinity. Don't care which.
  2438.             return x;
  2439.         }

  2440.         /* Divide the exponent by 3 */
  2441.         int exp3 = exponent / 3;

  2442.         /* p2 will be the nearest power of 2 to x with its exponent divided by 3 */
  2443.         double p2 = Double.longBitsToDouble((inbits & 0x8000000000000000L) | (long) (((exp3 + 1023) & 0x7ff)) << 52);

  2444.         /* This will be a number between 1 and 2 */
  2445.         final double mant = Double.longBitsToDouble((inbits & 0x000fffffffffffffL) | 0x3ff0000000000000L);

  2446.         /* Estimate the cube root of mant by polynomial */
  2447.         double est = -0.010714690733195933;
  2448.         est = est * mant + 0.0875862700108075;
  2449.         est = est * mant + -0.3058015757857271;
  2450.         est = est * mant + 0.7249995199969751;
  2451.         est = est * mant + 0.5039018405998233;

  2452.         est *= CBRTTWO[exponent % 3 + 2];

  2453.         // est should now be good to about 15 bits of precision.   Do 2 rounds of
  2454.         // Newton's method to get closer,  this should get us full double precision
  2455.         // Scale down x for the purpose of doing newtons method.  This avoids over/under flows.
  2456.         final double xs = x / (p2 * p2 * p2);
  2457.         est += (xs - est * est * est) / (3 * est * est);
  2458.         est += (xs - est * est * est) / (3 * est * est);

  2459.         // Do one round of Newton's method in extended precision to get the last bitright.
  2460.         double temp = est * HEX_40000000;
  2461.         double ya = est + temp - temp;
  2462.         double yb = est - ya;

  2463.         double za = ya * ya;
  2464.         double zb = ya * yb * 2.0 + yb * yb;
  2465.         temp = za * HEX_40000000;
  2466.         double temp2 = za + temp - temp;
  2467.         zb += za - temp2;
  2468.         za = temp2;

  2469.         zb = za * yb + ya * zb + zb * yb;
  2470.         za *= ya;

  2471.         double na = xs - za;
  2472.         double nb = -(na - xs + za);
  2473.         nb -= zb;

  2474.         est += (na + nb) / (3 * est * est);

  2475.         /* Scale by a power of two, so this is exact. */
  2476.         est *= p2;

  2477.         if (subnormal) {
  2478.             est *= 3.814697265625E-6; // 2^-18
  2479.         }

  2480.         return est;
  2481.     }

  2482.     /**
  2483.      *  Convert degrees to radians, with error of less than 0.5 ULP.
  2484.      *  @param x angle in degrees
  2485.      *  @return x converted into radians
  2486.      */
  2487.     public static double toRadians(double x) {
  2488.         if (Double.isInfinite(x) || x == 0.0) { // Matches +/- 0.0; return correct sign
  2489.             return x;
  2490.         }

  2491.         // These are PI/180 split into high and low order bits
  2492.         final double facta = 0.01745329052209854;
  2493.         final double factb = 1.997844754509471E-9;

  2494.         double xa = doubleHighPart(x);
  2495.         double xb = x - xa;

  2496.         double result = xb * factb + xb * facta + xa * factb + xa * facta;
  2497.         if (result == 0) {
  2498.             result *= x; // ensure correct sign if calculation underflows
  2499.         }
  2500.         return result;
  2501.     }

  2502.     /**
  2503.      *  Convert radians to degrees, with error of less than 0.5 ULP.
  2504.      *  @param x angle in radians
  2505.      *  @return x converted into degrees
  2506.      */
  2507.     public static double toDegrees(double x) {
  2508.         if (Double.isInfinite(x) || x == 0.0) { // Matches +/- 0.0; return correct sign
  2509.             return x;
  2510.         }

  2511.         // These are 180/PI split into high and low order bits
  2512.         final double facta = 57.2957763671875;
  2513.         final double factb = 3.145894820876798E-6;

  2514.         double xa = doubleHighPart(x);
  2515.         double xb = x - xa;

  2516.         return xb * factb + xb * facta + xa * factb + xa * facta;
  2517.     }

  2518.     /**
  2519.      * Absolute value.
  2520.      * @param x number from which absolute value is requested
  2521.      * @return abs(x)
  2522.      */
  2523.     public static int abs(final int x) {
  2524.         final int i = x >>> 31;
  2525.         return (x ^ (~i + 1)) + i;
  2526.     }

  2527.     /**
  2528.      * Absolute value.
  2529.      * @param x number from which absolute value is requested
  2530.      * @return abs(x)
  2531.      */
  2532.     public static long abs(final long x) {
  2533.         final long l = x >>> 63;
  2534.         // l is one if x negative zero else
  2535.         // ~l+1 is zero if x is positive, -1 if x is negative
  2536.         // x^(~l+1) is x is x is positive, ~x if x is negative
  2537.         // add around
  2538.         return (x ^ (~l + 1)) + l;
  2539.     }

  2540.     /**
  2541.      * Absolute value.
  2542.      * @param x number from which absolute value is requested
  2543.      * @return abs(x)
  2544.      */
  2545.     public static float abs(final float x) {
  2546.         return Float.intBitsToFloat(MASK_NON_SIGN_INT & Float.floatToRawIntBits(x));
  2547.     }

  2548.     /**
  2549.      * Absolute value.
  2550.      * @param x number from which absolute value is requested
  2551.      * @return abs(x)
  2552.      */
  2553.     public static double abs(double x) {
  2554.         return Double.longBitsToDouble(MASK_NON_SIGN_LONG & Double.doubleToRawLongBits(x));
  2555.     }

  2556.     /**
  2557.      * Compute least significant bit (Unit in Last Position) for a number.
  2558.      * @param x number from which ulp is requested
  2559.      * @return ulp(x)
  2560.      */
  2561.     public static double ulp(double x) {
  2562.         if (Double.isInfinite(x)) {
  2563.             return Double.POSITIVE_INFINITY;
  2564.         }
  2565.         return abs(x - Double.longBitsToDouble(Double.doubleToRawLongBits(x) ^ 1));
  2566.     }

  2567.     /**
  2568.      * Compute least significant bit (Unit in Last Position) for a number.
  2569.      * @param x number from which ulp is requested
  2570.      * @return ulp(x)
  2571.      */
  2572.     public static float ulp(float x) {
  2573.         if (Float.isInfinite(x)) {
  2574.             return Float.POSITIVE_INFINITY;
  2575.         }
  2576.         return abs(x - Float.intBitsToFloat(Float.floatToIntBits(x) ^ 1));
  2577.     }

  2578.     /**
  2579.      * Multiply a double number by a power of 2.
  2580.      * @param d number to multiply
  2581.      * @param n power of 2
  2582.      * @return d &times; 2<sup>n</sup>
  2583.      */
  2584.     public static double scalb(final double d, final int n) {

  2585.         // first simple and fast handling when 2^n can be represented using normal numbers
  2586.         if ((n > -1023) && (n < 1024)) {
  2587.             return d * Double.longBitsToDouble(((long) (n + 1023)) << 52);
  2588.         }

  2589.         // handle special cases
  2590.         if (Double.isNaN(d) || Double.isInfinite(d) || (d == 0)) {
  2591.             return d;
  2592.         }
  2593.         if (n < -2098) {
  2594.             return (d > 0) ? 0.0 : -0.0;
  2595.         }
  2596.         if (n > 2097) {
  2597.             return (d > 0) ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY;
  2598.         }

  2599.         // decompose d
  2600.         final long bits = Double.doubleToRawLongBits(d);
  2601.         final long sign = bits & 0x8000000000000000L;
  2602.         int  exponent   = ((int) (bits >>> 52)) & 0x7ff;
  2603.         long mantissa   = bits & 0x000fffffffffffffL;

  2604.         // compute scaled exponent
  2605.         int scaledExponent = exponent + n;

  2606.         if (n < 0) {
  2607.             // we are really in the case n <= -1023
  2608.             if (scaledExponent > 0) {
  2609.                 // both the input and the result are normal numbers, we only adjust the exponent
  2610.                 return Double.longBitsToDouble(sign | (((long) scaledExponent) << 52) | mantissa);
  2611.             } else if (scaledExponent > -53) {
  2612.                 // the input is a normal number and the result is a subnormal number

  2613.                 // recover the hidden mantissa bit
  2614.                 mantissa |= 1L << 52;

  2615.                 // scales down complete mantissa, hence losing least significant bits
  2616.                 final long mostSignificantLostBit = mantissa & (1L << (-scaledExponent));
  2617.                 mantissa >>>= 1 - scaledExponent;
  2618.                 if (mostSignificantLostBit != 0) {
  2619.                     // we need to add 1 bit to round up the result
  2620.                     mantissa++;
  2621.                 }
  2622.                 return Double.longBitsToDouble(sign | mantissa);
  2623.             } else {
  2624.                 // no need to compute the mantissa, the number scales down to 0
  2625.                 return (sign == 0L) ? 0.0 : -0.0;
  2626.             }
  2627.         } else {
  2628.             // we are really in the case n >= 1024
  2629.             if (exponent == 0) {

  2630.                 // the input number is subnormal, normalize it
  2631.                 while ((mantissa >>> 52) != 1) {
  2632.                     mantissa <<= 1;
  2633.                     --scaledExponent;
  2634.                 }
  2635.                 ++scaledExponent;
  2636.                 mantissa &= 0x000fffffffffffffL;

  2637.                 if (scaledExponent < 2047) {
  2638.                     return Double.longBitsToDouble(sign | (((long) scaledExponent) << 52) | mantissa);
  2639.                 } else {
  2640.                     return (sign == 0L) ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY;
  2641.                 }
  2642.             } else if (scaledExponent < 2047) {
  2643.                 return Double.longBitsToDouble(sign | (((long) scaledExponent) << 52) | mantissa);
  2644.             } else {
  2645.                 return (sign == 0L) ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY;
  2646.             }
  2647.         }
  2648.     }

  2649.     /**
  2650.      * Multiply a float number by a power of 2.
  2651.      * @param f number to multiply
  2652.      * @param n power of 2
  2653.      * @return f &times; 2<sup>n</sup>
  2654.      */
  2655.     public static float scalb(final float f, final int n) {

  2656.         // first simple and fast handling when 2^n can be represented using normal numbers
  2657.         if ((n > -127) && (n < 128)) {
  2658.             return f * Float.intBitsToFloat((n + 127) << 23);
  2659.         }

  2660.         // handle special cases
  2661.         if (Float.isNaN(f) || Float.isInfinite(f) || (f == 0f)) {
  2662.             return f;
  2663.         }
  2664.         if (n < -277) {
  2665.             return (f > 0) ? 0.0f : -0.0f;
  2666.         }
  2667.         if (n > 276) {
  2668.             return (f > 0) ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY;
  2669.         }

  2670.         // decompose f
  2671.         final int bits = Float.floatToIntBits(f);
  2672.         final int sign = bits & 0x80000000;
  2673.         int  exponent  = (bits >>> 23) & 0xff;
  2674.         int mantissa   = bits & 0x007fffff;

  2675.         // compute scaled exponent
  2676.         int scaledExponent = exponent + n;

  2677.         if (n < 0) {
  2678.             // we are really in the case n <= -127
  2679.             if (scaledExponent > 0) {
  2680.                 // both the input and the result are normal numbers, we only adjust the exponent
  2681.                 return Float.intBitsToFloat(sign | (scaledExponent << 23) | mantissa);
  2682.             } else if (scaledExponent > -24) {
  2683.                 // the input is a normal number and the result is a subnormal number

  2684.                 // recover the hidden mantissa bit
  2685.                 mantissa |= 1 << 23;

  2686.                 // scales down complete mantissa, hence losing least significant bits
  2687.                 final int mostSignificantLostBit = mantissa & (1 << (-scaledExponent));
  2688.                 mantissa >>>= 1 - scaledExponent;
  2689.                 if (mostSignificantLostBit != 0) {
  2690.                     // we need to add 1 bit to round up the result
  2691.                     mantissa++;
  2692.                 }
  2693.                 return Float.intBitsToFloat(sign | mantissa);
  2694.             } else {
  2695.                 // no need to compute the mantissa, the number scales down to 0
  2696.                 return (sign == 0) ? 0.0f : -0.0f;
  2697.             }
  2698.         } else {
  2699.             // we are really in the case n >= 128
  2700.             if (exponent == 0) {

  2701.                 // the input number is subnormal, normalize it
  2702.                 while ((mantissa >>> 23) != 1) {
  2703.                     mantissa <<= 1;
  2704.                     --scaledExponent;
  2705.                 }
  2706.                 ++scaledExponent;
  2707.                 mantissa &= 0x007fffff;

  2708.                 if (scaledExponent < 255) {
  2709.                     return Float.intBitsToFloat(sign | (scaledExponent << 23) | mantissa);
  2710.                 } else {
  2711.                     return (sign == 0) ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY;
  2712.                 }
  2713.             } else if (scaledExponent < 255) {
  2714.                 return Float.intBitsToFloat(sign | (scaledExponent << 23) | mantissa);
  2715.             } else {
  2716.                 return (sign == 0) ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY;
  2717.             }
  2718.         }
  2719.     }

  2720.     /**
  2721.      * Get the next machine representable number after a number, moving
  2722.      * in the direction of another number.
  2723.      * <p>
  2724.      * The ordering is as follows (increasing):
  2725.      * <ul>
  2726.      * <li>-INFINITY</li>
  2727.      * <li>-MAX_VALUE</li>
  2728.      * <li>-MIN_VALUE</li>
  2729.      * <li>-0.0</li>
  2730.      * <li>+0.0</li>
  2731.      * <li>+MIN_VALUE</li>
  2732.      * <li>+MAX_VALUE</li>
  2733.      * <li>+INFINITY</li>
  2734.      * <li></li>
  2735.      * </ul>
  2736.      * <p>
  2737.      * If arguments compare equal, then the second argument is returned.
  2738.      * <p>
  2739.      * If {@code direction} is greater than {@code d},
  2740.      * the smallest machine representable number strictly greater than
  2741.      * {@code d} is returned; if less, then the largest representable number
  2742.      * strictly less than {@code d} is returned.</p>
  2743.      * <p>
  2744.      * If {@code d} is infinite and direction does not
  2745.      * bring it back to finite numbers, it is returned unchanged.</p>
  2746.      *
  2747.      * @param d base number
  2748.      * @param direction (the only important thing is whether
  2749.      * {@code direction} is greater or smaller than {@code d})
  2750.      * @return the next machine representable number in the specified direction
  2751.      */
  2752.     public static double nextAfter(double d, double direction) {
  2753.         // handling of some important special cases
  2754.         if (Double.isNaN(d) || Double.isNaN(direction)) {
  2755.             return Double.NaN;
  2756.         } else if (d == direction) {
  2757.             return direction;
  2758.         } else if (Double.isInfinite(d)) {
  2759.             return (d < 0) ? -Double.MAX_VALUE : Double.MAX_VALUE;
  2760.         } else if (d == 0) {
  2761.             return (direction < 0) ? -Double.MIN_VALUE : Double.MIN_VALUE;
  2762.         }
  2763.         // special cases MAX_VALUE to infinity and  MIN_VALUE to 0
  2764.         // are handled just as normal numbers
  2765.         // can use raw bits since already dealt with infinity and NaN
  2766.         final long bits = Double.doubleToRawLongBits(d);
  2767.         final long sign = bits & 0x8000000000000000L;
  2768.         if ((direction < d) ^ (sign == 0L)) {
  2769.             return Double.longBitsToDouble(sign | ((bits & 0x7fffffffffffffffL) + 1));
  2770.         } else {
  2771.             return Double.longBitsToDouble(sign | ((bits & 0x7fffffffffffffffL) - 1));
  2772.         }
  2773.     }

  2774.     /**
  2775.      * Get the next machine representable number after a number, moving
  2776.      * in the direction of another number.
  2777.      * <p>
  2778.      * The ordering is as follows (increasing):
  2779.      * <ul>
  2780.      * <li>-INFINITY</li>
  2781.      * <li>-MAX_VALUE</li>
  2782.      * <li>-MIN_VALUE</li>
  2783.      * <li>-0.0</li>
  2784.      * <li>+0.0</li>
  2785.      * <li>+MIN_VALUE</li>
  2786.      * <li>+MAX_VALUE</li>
  2787.      * <li>+INFINITY</li>
  2788.      * <li></li>
  2789.      * </ul>
  2790.      * <p>
  2791.      * If arguments compare equal, then the second argument is returned.
  2792.      * <p>
  2793.      * If {@code direction} is greater than {@code f},
  2794.      * the smallest machine representable number strictly greater than
  2795.      * {@code f} is returned; if less, then the largest representable number
  2796.      * strictly less than {@code f} is returned.</p>
  2797.      * <p>
  2798.      * If {@code f} is infinite and direction does not
  2799.      * bring it back to finite numbers, it is returned unchanged.</p>
  2800.      *
  2801.      * @param f base number
  2802.      * @param direction (the only important thing is whether
  2803.      * {@code direction} is greater or smaller than {@code f})
  2804.      * @return the next machine representable number in the specified direction
  2805.      */
  2806.     public static float nextAfter(final float f, final double direction) {

  2807.         // handling of some important special cases
  2808.         if (Double.isNaN(f) || Double.isNaN(direction)) {
  2809.             return Float.NaN;
  2810.         } else if (f == direction) {
  2811.             return (float) direction;
  2812.         } else if (Float.isInfinite(f)) {
  2813.             return (f < 0f) ? -Float.MAX_VALUE : Float.MAX_VALUE;
  2814.         } else if (f == 0f) {
  2815.             return (direction < 0) ? -Float.MIN_VALUE : Float.MIN_VALUE;
  2816.         }
  2817.         // special cases MAX_VALUE to infinity and  MIN_VALUE to 0
  2818.         // are handled just as normal numbers

  2819.         final int bits = Float.floatToIntBits(f);
  2820.         final int sign = bits & 0x80000000;
  2821.         if ((direction < f) ^ (sign == 0)) {
  2822.             return Float.intBitsToFloat(sign | ((bits & 0x7fffffff) + 1));
  2823.         } else {
  2824.             return Float.intBitsToFloat(sign | ((bits & 0x7fffffff) - 1));
  2825.         }
  2826.     }

  2827.     /** Get the largest whole number smaller than x.
  2828.      * @param x number from which floor is requested
  2829.      * @return a double number f such that f is an integer f &lt;= x &lt; f + 1.0
  2830.      */
  2831.     public static double floor(double x) {
  2832.         long y;

  2833.         if (Double.isNaN(x)) {
  2834.             return x;
  2835.         }

  2836.         if (x >= TWO_POWER_52 || x <= -TWO_POWER_52) {
  2837.             return x;
  2838.         }

  2839.         y = (long) x;
  2840.         if (x < 0 && y != x) {
  2841.             y--;
  2842.         }

  2843.         if (y == 0) {
  2844.             return x * y;
  2845.         }

  2846.         return y;
  2847.     }

  2848.     /** Get the smallest whole number larger than x.
  2849.      * @param x number from which ceil is requested
  2850.      * @return a double number c such that c is an integer c - 1.0 &lt; x &lt;= c
  2851.      */
  2852.     public static double ceil(double x) {
  2853.         double y;

  2854.         if (Double.isNaN(x)) {
  2855.             return x;
  2856.         }

  2857.         y = floor(x);
  2858.         if (y == x) {
  2859.             return y;
  2860.         }

  2861.         y += 1.0;

  2862.         if (y == 0) {
  2863.             return x * y;
  2864.         }

  2865.         return y;
  2866.     }

  2867.     /** Get the whole number that is the nearest to x, or the even one if x is exactly half way between two integers.
  2868.      * @param x number from which nearest whole number is requested
  2869.      * @return a double number r such that r is an integer r - 0.5 &lt;= x &lt;= r + 0.5
  2870.      */
  2871.     public static double rint(double x) {
  2872.         double y = floor(x);
  2873.         double d = x - y;

  2874.         if (d > 0.5) {
  2875.             if (y == -1.0) {
  2876.                 return -0.0; // Preserve sign of operand
  2877.             }
  2878.             return y + 1.0;
  2879.         }
  2880.         if (d < 0.5) {
  2881.             return y;
  2882.         }

  2883.         /* half way, round to even */
  2884.         long z = (long) y;
  2885.         return (z & 1) == 0 ? y : y + 1.0;
  2886.     }

  2887.     /** Get the closest long to x.
  2888.      * @param x number from which closest long is requested
  2889.      * @return closest long to x
  2890.      */
  2891.     public static long round(double x) {
  2892.         final long bits = Double.doubleToRawLongBits(x);
  2893.         final int biasedExp = ((int) (bits >> 52)) & 0x7ff;
  2894.         // Shift to get rid of bits past comma except first one: will need to
  2895.         // 1-shift to the right to end up with correct magnitude.
  2896.         final int shift = (52 - 1 + Double.MAX_EXPONENT) - biasedExp;
  2897.         if ((shift & -64) == 0) {
  2898.             // shift in [0,63], so unbiased exp in [-12,51].
  2899.             long extendedMantissa = 0x0010000000000000L | (bits & 0x000fffffffffffffL);
  2900.             if (bits < 0) {
  2901.                 extendedMantissa = -extendedMantissa;
  2902.             }
  2903.             // If value is positive and first bit past comma is 0, rounding
  2904.             // to lower integer, else to upper one, which is what "+1" and
  2905.             // then ">>1" do.
  2906.             return ((extendedMantissa >> shift) + 1L) >> 1;
  2907.         } else {
  2908.             // +-Infinity, NaN, or a mathematical integer.
  2909.             return (long) x;
  2910.         }
  2911.     }

  2912.     /** Get the closest int to x.
  2913.      * @param x number from which closest int is requested
  2914.      * @return closest int to x
  2915.      */
  2916.     public static int round(final float x) {
  2917.         final int bits = Float.floatToRawIntBits(x);
  2918.         final int biasedExp = (bits >> 23) & 0xff;
  2919.         // Shift to get rid of bits past comma except first one: will need to
  2920.         // 1-shift to the right to end up with correct magnitude.
  2921.         final int shift = (23 - 1 + Float.MAX_EXPONENT) - biasedExp;
  2922.         if ((shift & -32) == 0) {
  2923.             // shift in [0,31], so unbiased exp in [-9,22].
  2924.             int extendedMantissa = 0x00800000 | (bits & 0x007fffff);
  2925.             if (bits < 0) {
  2926.                 extendedMantissa = -extendedMantissa;
  2927.             }
  2928.             // If value is positive and first bit past comma is 0, rounding
  2929.             // to lower integer, else to upper one, which is what "+1" and
  2930.             // then ">>1" do.
  2931.             return ((extendedMantissa >> shift) + 1) >> 1;
  2932.         } else {
  2933.             // +-Infinity, NaN, or a mathematical integer.
  2934.             return (int) x;
  2935.         }
  2936.     }

  2937.     /** Compute the minimum of two values.
  2938.      * @param a first value
  2939.      * @param b second value
  2940.      * @return a if a is lesser or equal to b, b otherwise
  2941.      */
  2942.     public static int min(final int a, final int b) {
  2943.         return (a <= b) ? a : b;
  2944.     }

  2945.     /** Compute the minimum of two values.
  2946.      * @param a first value
  2947.      * @param b second value
  2948.      * @return a if a is lesser or equal to b, b otherwise
  2949.      */
  2950.     public static long min(final long a, final long b) {
  2951.         return (a <= b) ? a : b;
  2952.     }

  2953.     /** Compute the minimum of two values.
  2954.      * @param a first value
  2955.      * @param b second value
  2956.      * @return a if a is lesser or equal to b, b otherwise
  2957.      */
  2958.     public static float min(final float a, final float b) {
  2959.         if (a > b) {
  2960.             return b;
  2961.         }
  2962.         if (a < b) {
  2963.             return a;
  2964.         }
  2965.         /* if either arg is NaN, return NaN */
  2966.         if (a != b) {
  2967.             return Float.NaN;
  2968.         }
  2969.         /* min(+0.0,-0.0) == -0.0 */
  2970.         /* 0x80000000 == Float.floatToRawIntBits(-0.0d) */
  2971.         int bits = Float.floatToRawIntBits(a);
  2972.         if (bits == 0x80000000) {
  2973.             return a;
  2974.         }
  2975.         return b;
  2976.     }

  2977.     /** Compute the minimum of two values.
  2978.      * @param a first value
  2979.      * @param b second value
  2980.      * @return a if a is lesser or equal to b, b otherwise
  2981.      */
  2982.     public static double min(final double a, final double b) {
  2983.         if (a > b) {
  2984.             return b;
  2985.         }
  2986.         if (a < b) {
  2987.             return a;
  2988.         }
  2989.         /* if either arg is NaN, return NaN */
  2990.         if (a != b) {
  2991.             return Double.NaN;
  2992.         }
  2993.         /* min(+0.0,-0.0) == -0.0 */
  2994.         /* 0x8000000000000000L == Double.doubleToRawLongBits(-0.0d) */
  2995.         long bits = Double.doubleToRawLongBits(a);
  2996.         if (bits == 0x8000000000000000L) {
  2997.             return a;
  2998.         }
  2999.         return b;
  3000.     }

  3001.     /** Compute the maximum of two values.
  3002.      * @param a first value
  3003.      * @param b second value
  3004.      * @return b if a is lesser or equal to b, a otherwise
  3005.      */
  3006.     public static int max(final int a, final int b) {
  3007.         return (a <= b) ? b : a;
  3008.     }

  3009.     /** Compute the maximum of two values.
  3010.      * @param a first value
  3011.      * @param b second value
  3012.      * @return b if a is lesser or equal to b, a otherwise
  3013.      */
  3014.     public static long max(final long a, final long b) {
  3015.         return (a <= b) ? b : a;
  3016.     }

  3017.     /** Compute the maximum of two values.
  3018.      * @param a first value
  3019.      * @param b second value
  3020.      * @return b if a is lesser or equal to b, a otherwise
  3021.      */
  3022.     public static float max(final float a, final float b) {
  3023.         if (a > b) {
  3024.             return a;
  3025.         }
  3026.         if (a < b) {
  3027.             return b;
  3028.         }
  3029.         /* if either arg is NaN, return NaN */
  3030.         if (a != b) {
  3031.             return Float.NaN;
  3032.         }
  3033.         /* min(+0.0,-0.0) == -0.0 */
  3034.         /* 0x80000000 == Float.floatToRawIntBits(-0.0d) */
  3035.         int bits = Float.floatToRawIntBits(a);
  3036.         if (bits == 0x80000000) {
  3037.             return b;
  3038.         }
  3039.         return a;
  3040.     }

  3041.     /** Compute the maximum of two values.
  3042.      * @param a first value
  3043.      * @param b second value
  3044.      * @return b if a is lesser or equal to b, a otherwise
  3045.      */
  3046.     public static double max(final double a, final double b) {
  3047.         if (a > b) {
  3048.             return a;
  3049.         }
  3050.         if (a < b) {
  3051.             return b;
  3052.         }
  3053.         /* if either arg is NaN, return NaN */
  3054.         if (a != b) {
  3055.             return Double.NaN;
  3056.         }
  3057.         /* min(+0.0,-0.0) == -0.0 */
  3058.         /* 0x8000000000000000L == Double.doubleToRawLongBits(-0.0d) */
  3059.         long bits = Double.doubleToRawLongBits(a);
  3060.         if (bits == 0x8000000000000000L) {
  3061.             return b;
  3062.         }
  3063.         return a;
  3064.     }

  3065.     /**
  3066.      * Returns the hypotenuse of a triangle with sides {@code x} and {@code y}
  3067.      * - sqrt(<i>x</i><sup>2</sup>&nbsp;+<i>y</i><sup>2</sup>)<br>
  3068.      * avoiding intermediate overflow or underflow.
  3069.      *
  3070.      * <ul>
  3071.      * <li> If either argument is infinite, then the result is positive infinity.</li>
  3072.      * <li> else, if either argument is NaN then the result is NaN.</li>
  3073.      * </ul>
  3074.      *
  3075.      * @param x a value
  3076.      * @param y a value
  3077.      * @return sqrt(<i>x</i><sup>2</sup>&nbsp;+<i>y</i><sup>2</sup>)
  3078.      */
  3079.     public static double hypot(final double x, final double y) {
  3080.         if (Double.isInfinite(x) || Double.isInfinite(y)) {
  3081.             return Double.POSITIVE_INFINITY;
  3082.         } else if (Double.isNaN(x) || Double.isNaN(y)) {
  3083.             return Double.NaN;
  3084.         } else {
  3085.             final int expX = getExponent(x);
  3086.             final int expY = getExponent(y);
  3087.             if (expX > expY + 27) {
  3088.                 // y is neglectible with respect to x
  3089.                 return abs(x);
  3090.             } else if (expY > expX + 27) {
  3091.                 // x is neglectible with respect to y
  3092.                 return abs(y);
  3093.             } else {
  3094.                 // find an intermediate scale to avoid both overflow and underflow
  3095.                 final int middleExp = (expX + expY) / 2;

  3096.                 // scale parameters without losing precision
  3097.                 final double scaledX = scalb(x, -middleExp);
  3098.                 final double scaledY = scalb(y, -middleExp);

  3099.                 // compute scaled hypotenuse
  3100.                 final double scaledH = Math.sqrt(scaledX * scaledX + scaledY * scaledY);

  3101.                 // remove scaling
  3102.                 return scalb(scaledH, middleExp);
  3103.             }
  3104.         }
  3105.     }

  3106.     /**
  3107.      * Computes the remainder as prescribed by the IEEE 754 standard.
  3108.      * The remainder value is mathematically equal to {@code x - y*n}
  3109.      * where {@code n} is the mathematical integer closest to the exact mathematical value
  3110.      * of the quotient {@code x/y}.
  3111.      * If two mathematical integers are equally close to {@code x/y} then
  3112.      * {@code n} is the integer that is even.
  3113.      * <ul>
  3114.      * <li>If either operand is NaN, the result is NaN.</li>
  3115.      * <li>If the result is not NaN, the sign of the result equals the sign of the dividend.</li>
  3116.      * <li>If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN.</li>
  3117.      * <li>If the dividend is finite and the divisor is an infinity, the result equals the dividend.</li>
  3118.      * <li>If the dividend is a zero and the divisor is finite, the result equals the dividend.</li>
  3119.      * </ul>
  3120.      * @param dividend the number to be divided
  3121.      * @param divisor the number by which to divide
  3122.      * @return the remainder, rounded
  3123.      */
  3124.     public static double IEEEremainder(final double dividend, final double divisor) {
  3125.         if (getExponent(dividend) == 1024 || getExponent(divisor) == 1024 || divisor == 0.0) {
  3126.             // we are in one of the special cases
  3127.             if (Double.isInfinite(divisor) && !Double.isInfinite(dividend)) {
  3128.                 return dividend;
  3129.             } else {
  3130.                 return Double.NaN;
  3131.             }
  3132.         } else {
  3133.             // we are in the general case
  3134.             final double n         = AccurateMath.rint(dividend / divisor);
  3135.             final double remainder = Double.isInfinite(n) ? 0.0 : dividend - divisor * n;
  3136.             return (remainder == 0) ? AccurateMath.copySign(remainder, dividend) : remainder;
  3137.         }
  3138.     }

  3139.     /** Convert a long to integer, detecting overflows.
  3140.      * @param n number to convert to int
  3141.      * @return integer with same value as n if no overflows occur
  3142.      * @exception ArithmeticException if n cannot fit into an int
  3143.      * @since 3.4
  3144.      */
  3145.     public static int toIntExact(final long n) {
  3146.         if (n < Integer.MIN_VALUE ||
  3147.             n > Integer.MAX_VALUE) {
  3148.             throw new ArithmeticException(OVERFLOW_MSG);
  3149.         }
  3150.         return (int) n;
  3151.     }

  3152.     /** Increment a number, detecting overflows.
  3153.      * @param n number to increment
  3154.      * @return n+1 if no overflows occur
  3155.      * @exception ArithmeticException if an overflow occurs
  3156.      * @since 3.4
  3157.      */
  3158.     public static int incrementExact(final int n) {
  3159.         if (n == Integer.MAX_VALUE) {
  3160.             throw new ArithmeticException(OVERFLOW_MSG);
  3161.         }
  3162.         return n + 1;
  3163.     }

  3164.     /** Increment a number, detecting overflows.
  3165.      * @param n number to increment
  3166.      * @return n+1 if no overflows occur
  3167.      * @exception ArithmeticException if an overflow occurs
  3168.      * @since 3.4
  3169.      */
  3170.     public static long incrementExact(final long n) {
  3171.         if (n == Long.MAX_VALUE) {
  3172.             throw new ArithmeticException(OVERFLOW_MSG);
  3173.         }
  3174.         return n + 1;
  3175.     }

  3176.     /** Decrement a number, detecting overflows.
  3177.      * @param n number to decrement
  3178.      * @return n-1 if no overflows occur
  3179.      * @exception ArithmeticException if an overflow occurs
  3180.      * @since 3.4
  3181.      */
  3182.     public static int decrementExact(final int n) {
  3183.         if (n == Integer.MIN_VALUE) {
  3184.             throw new ArithmeticException(OVERFLOW_MSG);
  3185.         }
  3186.         return n - 1;
  3187.     }

  3188.     /** Decrement a number, detecting overflows.
  3189.      * @param n number to decrement
  3190.      * @return n-1 if no overflows occur
  3191.      * @exception ArithmeticException if an overflow occurs
  3192.      * @since 3.4
  3193.      */
  3194.     public static long decrementExact(final long n) {
  3195.         if (n == Long.MIN_VALUE) {
  3196.             throw new ArithmeticException(OVERFLOW_MSG);
  3197.         }
  3198.         return n - 1;
  3199.     }

  3200.     /** Add two numbers, detecting overflows.
  3201.      * @param a first number to add
  3202.      * @param b second number to add
  3203.      * @return a+b if no overflows occur
  3204.      * @exception ArithmeticException if an overflow occurs
  3205.      * @since 3.4
  3206.      */
  3207.     public static int addExact(final int a, final int b) {
  3208.         // compute sum
  3209.         final int sum = a + b;

  3210.         // check for overflow
  3211.         if ((a ^ b) >= 0 &&
  3212.             (sum ^ b) < 0) {
  3213.             throw new ArithmeticException(OVERFLOW_MSG);
  3214.         }

  3215.         return sum;
  3216.     }

  3217.     /** Add two numbers, detecting overflows.
  3218.      * @param a first number to add
  3219.      * @param b second number to add
  3220.      * @return a+b if no overflows occur
  3221.      * @exception ArithmeticException if an overflow occurs
  3222.      * @since 3.4
  3223.      */
  3224.     public static long addExact(final long a, final long b) {
  3225.         // compute sum
  3226.         final long sum = a + b;

  3227.         // check for overflow
  3228.         if ((a ^ b) >= 0 &&
  3229.             (sum ^ b) < 0) {
  3230.             throw new ArithmeticException(OVERFLOW_MSG);
  3231.         }

  3232.         return sum;
  3233.     }

  3234.     /** Subtract two numbers, detecting overflows.
  3235.      * @param a first number
  3236.      * @param b second number to subtract from a
  3237.      * @return a-b if no overflows occur
  3238.      * @exception ArithmeticException if an overflow occurs
  3239.      * @since 3.4
  3240.      */
  3241.     public static int subtractExact(final int a, final int b) {
  3242.         // compute subtraction
  3243.         final int sub = a - b;

  3244.         // check for overflow
  3245.         if ((a ^ b) < 0 &&
  3246.             (sub ^ b) >= 0) {
  3247.             throw new ArithmeticException(OVERFLOW_MSG);
  3248.         }

  3249.         return sub;
  3250.     }

  3251.     /** Subtract two numbers, detecting overflows.
  3252.      * @param a first number
  3253.      * @param b second number to subtract from a
  3254.      * @return a-b if no overflows occur
  3255.      * @exception ArithmeticException if an overflow occurs
  3256.      * @since 3.4
  3257.      */
  3258.     public static long subtractExact(final long a, final long b) {
  3259.         // compute subtraction
  3260.         final long sub = a - b;

  3261.         // check for overflow
  3262.         if ((a ^ b) < 0 &&
  3263.             (sub ^ b) >= 0) {
  3264.             throw new ArithmeticException(OVERFLOW_MSG);
  3265.         }

  3266.         return sub;
  3267.     }

  3268.     /** Multiply two numbers, detecting overflows.
  3269.      * @param a first number to multiply
  3270.      * @param b second number to multiply
  3271.      * @return a*b if no overflows occur
  3272.      * @exception ArithmeticException if an overflow occurs
  3273.      * @since 3.4
  3274.      */
  3275.     public static int multiplyExact(final int a, final int b) {
  3276.         if (((b > 0) &&
  3277.              (a > Integer.MAX_VALUE / b ||
  3278.               a < Integer.MIN_VALUE / b)) ||
  3279.             ((b < -1) &&
  3280.              (a > Integer.MIN_VALUE / b ||
  3281.               a < Integer.MAX_VALUE / b)) ||
  3282.             ((b == -1) &&
  3283.              (a == Integer.MIN_VALUE))) {
  3284.             throw new ArithmeticException(OVERFLOW_MSG);
  3285.         }
  3286.         return a * b;
  3287.     }

  3288.     /** Multiply two numbers, detecting overflows.
  3289.      * @param a first number to multiply
  3290.      * @param b second number to multiply
  3291.      * @return a*b if no overflows occur
  3292.      * @exception ArithmeticException if an overflow occurs
  3293.      * @since 3.4
  3294.      */
  3295.     public static long multiplyExact(final long a, final long b) {
  3296.         if (((b  >  0L) &&
  3297.              (a > Long.MAX_VALUE / b ||
  3298.               a < Long.MIN_VALUE / b)) ||
  3299.             ((b  < -1L) &&
  3300.              (a > Long.MIN_VALUE / b ||
  3301.               a < Long.MAX_VALUE / b)) ||
  3302.             ((b == -1L) &&
  3303.              (a == Long.MIN_VALUE))) {
  3304.             throw new ArithmeticException(OVERFLOW_MSG);
  3305.         }
  3306.         return a * b;
  3307.     }

  3308.     /** Finds q such that a = q b + r with 0 &lt;= r &lt; b if b &gt; 0 and b &lt; r &lt;= 0 if b &lt; 0.
  3309.      * <p>
  3310.      * This methods returns the same value as integer division when
  3311.      * a and b are same signs, but returns a different value when
  3312.      * they are opposite (i.e. q is negative).
  3313.      * </p>
  3314.      * @param a dividend
  3315.      * @param b divisor
  3316.      * @return q such that a = q b + r with 0 &lt;= r &lt; b if b &gt; 0 and b &lt; r &lt;= 0 if b &lt; 0
  3317.      * @exception ArithmeticException if b == 0
  3318.      * @see #floorMod(int, int)
  3319.      * @since 3.4
  3320.      */
  3321.     public static int floorDiv(final int a, final int b) {
  3322.         if (b == 0) {
  3323.             throw new ArithmeticException(ZERO_DENOMINATOR_MSG);
  3324.         }

  3325.         final int m = a % b;
  3326.         if ((a ^ b) >= 0 || m == 0) {
  3327.             // a an b have same sign, or division is exact
  3328.             return a / b;
  3329.         } else {
  3330.             // a and b have opposite signs and division is not exact
  3331.             return (a / b) - 1;
  3332.         }
  3333.     }

  3334.     /** Finds q such that a = q b + r with 0 &lt;= r &lt; b if b &gt; 0 and b &lt; r &lt;= 0 if b &lt; 0.
  3335.      * <p>
  3336.      * This methods returns the same value as integer division when
  3337.      * a and b are same signs, but returns a different value when
  3338.      * they are opposite (i.e. q is negative).
  3339.      * </p>
  3340.      * @param a dividend
  3341.      * @param b divisor
  3342.      * @return q such that a = q b + r with 0 &lt;= r &lt; b if b &gt; 0 and b &lt; r &lt;= 0 if b &lt; 0
  3343.      * @exception ArithmeticException if b == 0
  3344.      * @see #floorMod(long, long)
  3345.      * @since 3.4
  3346.      */
  3347.     public static long floorDiv(final long a, final long b) {
  3348.         if (b == 0L) {
  3349.             throw new ArithmeticException(ZERO_DENOMINATOR_MSG);
  3350.         }

  3351.         final long m = a % b;
  3352.         if ((a ^ b) >= 0L || m == 0L) {
  3353.             // a an b have same sign, or division is exact
  3354.             return a / b;
  3355.         } else {
  3356.             // a and b have opposite signs and division is not exact
  3357.             return (a / b) - 1L;
  3358.         }
  3359.     }

  3360.     /** Finds r such that a = q b + r with 0 &lt;= r &lt; b if b &gt; 0 and b &lt; r &lt;= 0 if b &lt; 0.
  3361.      * <p>
  3362.      * This methods returns the same value as integer modulo when
  3363.      * a and b are same signs, but returns a different value when
  3364.      * they are opposite (i.e. q is negative).
  3365.      * </p>
  3366.      * @param a dividend
  3367.      * @param b divisor
  3368.      * @return r such that a = q b + r with 0 &lt;= r &lt; b if b &gt; 0 and b &lt; r &lt;= 0 if b &lt; 0
  3369.      * @exception ArithmeticException if b == 0
  3370.      * @see #floorDiv(int, int)
  3371.      * @since 3.4
  3372.      */
  3373.     public static int floorMod(final int a, final int b) {
  3374.         if (b == 0) {
  3375.             throw new ArithmeticException(ZERO_DENOMINATOR_MSG);
  3376.         }

  3377.         final int m = a % b;
  3378.         if ((a ^ b) >= 0 || m == 0) {
  3379.             // a an b have same sign, or division is exact
  3380.             return m;
  3381.         } else {
  3382.             // a and b have opposite signs and division is not exact
  3383.             return b + m;
  3384.         }
  3385.     }

  3386.     /** Finds r such that a = q b + r with 0 &lt;= r &lt; b if b &gt; 0 and b &lt; r &lt;= 0 if b &lt; 0.
  3387.      * <p>
  3388.      * This methods returns the same value as integer modulo when
  3389.      * a and b are same signs, but returns a different value when
  3390.      * they are opposite (i.e. q is negative).
  3391.      * </p>
  3392.      * @param a dividend
  3393.      * @param b divisor
  3394.      * @return r such that a = q b + r with 0 &lt;= r &lt; b if b &gt; 0 and b &lt; r &lt;= 0 if b &lt; 0
  3395.      * @exception ArithmeticException if b == 0
  3396.      * @see #floorDiv(long, long)
  3397.      * @since 3.4
  3398.      */
  3399.     public static long floorMod(final long a, final long b) {
  3400.         if (b == 0L) {
  3401.             throw new ArithmeticException(ZERO_DENOMINATOR_MSG);
  3402.         }

  3403.         final long m = a % b;
  3404.         if ((a ^ b) >= 0L || m == 0L) {
  3405.             // a an b have same sign, or division is exact
  3406.             return m;
  3407.         } else {
  3408.             // a and b have opposite signs and division is not exact
  3409.             return b + m;
  3410.         }
  3411.     }

  3412.     /**
  3413.      * Returns the first argument with the sign of the second argument.
  3414.      * A NaN {@code sign} argument is treated as positive.
  3415.      *
  3416.      * @param magnitude the value to return
  3417.      * @param sign the sign for the returned value
  3418.      * @return the magnitude with the same sign as the {@code sign} argument
  3419.      */
  3420.     public static double copySign(double magnitude, double sign) {
  3421.         // The highest order bit is going to be zero if the
  3422.         // highest order bit of m and s is the same and one otherwise.
  3423.         // So (m^s) will be positive if both m and s have the same sign
  3424.         // and negative otherwise.
  3425.         final long m = Double.doubleToRawLongBits(magnitude); // don't care about NaN
  3426.         final long s = Double.doubleToRawLongBits(sign);
  3427.         if ((m ^ s) >= 0) {
  3428.             return magnitude;
  3429.         }
  3430.         return -magnitude; // flip sign
  3431.     }

  3432.     /**
  3433.      * Returns the first argument with the sign of the second argument.
  3434.      * A NaN {@code sign} argument is treated as positive.
  3435.      *
  3436.      * @param magnitude the value to return
  3437.      * @param sign the sign for the returned value
  3438.      * @return the magnitude with the same sign as the {@code sign} argument
  3439.      */
  3440.     public static float copySign(float magnitude, float sign) {
  3441.         // The highest order bit is going to be zero if the
  3442.         // highest order bit of m and s is the same and one otherwise.
  3443.         // So (m^s) will be positive if both m and s have the same sign
  3444.         // and negative otherwise.
  3445.         final int m = Float.floatToRawIntBits(magnitude);
  3446.         final int s = Float.floatToRawIntBits(sign);
  3447.         if ((m ^ s) >= 0) {
  3448.             return magnitude;
  3449.         }
  3450.         return -magnitude; // flip sign
  3451.     }

  3452.     /**
  3453.      * Return the exponent of a double number, removing the bias.
  3454.      * <p>
  3455.      * For double numbers of the form 2<sup>x</sup>, the unbiased
  3456.      * exponent is exactly x.
  3457.      * </p>
  3458.      * @param d number from which exponent is requested
  3459.      * @return exponent for d in IEEE754 representation, without bias
  3460.      */
  3461.     public static int getExponent(final double d) {
  3462.         // NaN and Infinite will return 1024 anywho so can use raw bits
  3463.         return (int) ((Double.doubleToRawLongBits(d) >>> 52) & 0x7ff) - 1023;
  3464.     }

  3465.     /**
  3466.      * Return the exponent of a float number, removing the bias.
  3467.      * <p>
  3468.      * For float numbers of the form 2<sup>x</sup>, the unbiased
  3469.      * exponent is exactly x.
  3470.      * </p>
  3471.      * @param f number from which exponent is requested
  3472.      * @return exponent for d in IEEE754 representation, without bias
  3473.      */
  3474.     public static int getExponent(final float f) {
  3475.         // NaN and Infinite will return the same exponent anywho so can use raw bits
  3476.         return ((Float.floatToRawIntBits(f) >>> 23) & 0xff) - 127;
  3477.     }

  3478.     /**
  3479.      * Print out contents of arrays, and check the length.
  3480.      * <p>used to generate the preset arrays originally.</p>
  3481.      * @param a unused
  3482.      */
  3483.     public static void main(String[] a) {
  3484.         PrintStream out = System.out;
  3485.         AccurateMathCalc.printarray(out, "EXP_INT_TABLE_A", EXP_INT_TABLE_LEN, ExpIntTable.EXP_INT_TABLE_A);
  3486.         AccurateMathCalc.printarray(out, "EXP_INT_TABLE_B", EXP_INT_TABLE_LEN, ExpIntTable.EXP_INT_TABLE_B);
  3487.         AccurateMathCalc.printarray(out, "EXP_FRAC_TABLE_A", EXP_FRAC_TABLE_LEN, ExpFracTable.EXP_FRAC_TABLE_A);
  3488.         AccurateMathCalc.printarray(out, "EXP_FRAC_TABLE_B", EXP_FRAC_TABLE_LEN, ExpFracTable.EXP_FRAC_TABLE_B);
  3489.         AccurateMathCalc.printarray(out, "LN_MANT", LN_MANT_LEN, lnMant.LN_MANT);
  3490.         AccurateMathCalc.printarray(out, "SINE_TABLE_A", SINE_TABLE_LEN, SINE_TABLE_A);
  3491.         AccurateMathCalc.printarray(out, "SINE_TABLE_B", SINE_TABLE_LEN, SINE_TABLE_B);
  3492.         AccurateMathCalc.printarray(out, "COSINE_TABLE_A", SINE_TABLE_LEN, COSINE_TABLE_A);
  3493.         AccurateMathCalc.printarray(out, "COSINE_TABLE_B", SINE_TABLE_LEN, COSINE_TABLE_B);
  3494.         AccurateMathCalc.printarray(out, "TANGENT_TABLE_A", SINE_TABLE_LEN, TANGENT_TABLE_A);
  3495.         AccurateMathCalc.printarray(out, "TANGENT_TABLE_B", SINE_TABLE_LEN, TANGENT_TABLE_B);
  3496.     }

  3497.     /** Enclose large data table in nested static class so it's only loaded on first access. */
  3498.     private static final class ExpIntTable {
  3499.         /** Exponential evaluated at integer values,
  3500.          * exp(x) =  expIntTableA[x + EXP_INT_TABLE_MAX_INDEX] + expIntTableB[x+EXP_INT_TABLE_MAX_INDEX].
  3501.          */
  3502.         private static final double[] EXP_INT_TABLE_A;
  3503.         /** Exponential evaluated at integer values.
  3504.          * exp(x) =  expIntTableA[x + EXP_INT_TABLE_MAX_INDEX] + expIntTableB[x+EXP_INT_TABLE_MAX_INDEX]
  3505.          */
  3506.         private static final double[] EXP_INT_TABLE_B;

  3507.         static {
  3508.             if (RECOMPUTE_TABLES_AT_RUNTIME) {
  3509.                 EXP_INT_TABLE_A = new double[AccurateMath.EXP_INT_TABLE_LEN];
  3510.                 EXP_INT_TABLE_B = new double[AccurateMath.EXP_INT_TABLE_LEN];

  3511.                 final double[] tmp = new double[2];
  3512.                 final double[] recip = new double[2];

  3513.                 // Populate expIntTable
  3514.                 for (int i = 0; i < AccurateMath.EXP_INT_TABLE_MAX_INDEX; i++) {
  3515.                     AccurateMathCalc.expint(i, tmp);
  3516.                     EXP_INT_TABLE_A[i + AccurateMath.EXP_INT_TABLE_MAX_INDEX] = tmp[0];
  3517.                     EXP_INT_TABLE_B[i + AccurateMath.EXP_INT_TABLE_MAX_INDEX] = tmp[1];

  3518.                     if (i != 0) {
  3519.                         // Negative integer powers
  3520.                         AccurateMathCalc.splitReciprocal(tmp, recip);
  3521.                         EXP_INT_TABLE_A[AccurateMath.EXP_INT_TABLE_MAX_INDEX - i] = recip[0];
  3522.                         EXP_INT_TABLE_B[AccurateMath.EXP_INT_TABLE_MAX_INDEX - i] = recip[1];
  3523.                     }
  3524.                 }
  3525.             } else {
  3526.                 EXP_INT_TABLE_A = AccurateMathLiteralArrays.loadExpIntA();
  3527.                 EXP_INT_TABLE_B = AccurateMathLiteralArrays.loadExpIntB();
  3528.             }
  3529.         }
  3530.     }

  3531.     /** Enclose large data table in nested static class so it's only loaded on first access. */
  3532.     private static final class ExpFracTable {
  3533.         /** Exponential over the range of 0 - 1 in increments of 2^-10
  3534.          * exp(x/1024) =  expFracTableA[x] + expFracTableB[x].
  3535.          * 1024 = 2^10
  3536.          */
  3537.         private static final double[] EXP_FRAC_TABLE_A;
  3538.         /** Exponential over the range of 0 - 1 in increments of 2^-10
  3539.          * exp(x/1024) =  expFracTableA[x] + expFracTableB[x].
  3540.          */
  3541.         private static final double[] EXP_FRAC_TABLE_B;

  3542.         static {
  3543.             if (RECOMPUTE_TABLES_AT_RUNTIME) {
  3544.                 EXP_FRAC_TABLE_A = new double[AccurateMath.EXP_FRAC_TABLE_LEN];
  3545.                 EXP_FRAC_TABLE_B = new double[AccurateMath.EXP_FRAC_TABLE_LEN];

  3546.                 final double[] tmp = new double[2];

  3547.                 // Populate expFracTable
  3548.                 final double factor = 1d / (EXP_FRAC_TABLE_LEN - 1);
  3549.                 for (int i = 0; i < EXP_FRAC_TABLE_A.length; i++) {
  3550.                     AccurateMathCalc.slowexp(i * factor, tmp);
  3551.                     EXP_FRAC_TABLE_A[i] = tmp[0];
  3552.                     EXP_FRAC_TABLE_B[i] = tmp[1];
  3553.                 }
  3554.             } else {
  3555.                 EXP_FRAC_TABLE_A = AccurateMathLiteralArrays.loadExpFracA();
  3556.                 EXP_FRAC_TABLE_B = AccurateMathLiteralArrays.loadExpFracB();
  3557.             }
  3558.         }
  3559.     }

  3560.     /** Enclose large data table in nested static class so it's only loaded on first access. */
  3561.     private static final class lnMant {
  3562.         /** Extended precision logarithm table over the range 1 - 2 in increments of 2^-10. */
  3563.         private static final double[][] LN_MANT;

  3564.         static {
  3565.             if (RECOMPUTE_TABLES_AT_RUNTIME) {
  3566.                 LN_MANT = new double[AccurateMath.LN_MANT_LEN][];

  3567.                 // Populate lnMant table
  3568.                 for (int i = 0; i < LN_MANT.length; i++) {
  3569.                     final double d = Double.longBitsToDouble((((long) i) << 42) | 0x3ff0000000000000L);
  3570.                     LN_MANT[i] = AccurateMathCalc.slowLog(d);
  3571.                 }
  3572.             } else {
  3573.                 LN_MANT = AccurateMathLiteralArrays.loadLnMant();
  3574.             }
  3575.         }
  3576.     }

  3577.     /** Enclose the Cody/Waite reduction (used in "sin", "cos" and "tan"). */
  3578.     private static class CodyWaite {
  3579.         /** k. */
  3580.         private final int finalK;
  3581.         /** remA. */
  3582.         private final double finalRemA;
  3583.         /** remB. */
  3584.         private final double finalRemB;

  3585.         /**
  3586.          * @param xa Argument.
  3587.          */
  3588.         CodyWaite(double xa) {
  3589.             // Estimate k.
  3590.             //k = (int)(xa / 1.5707963267948966);
  3591.             int k = (int)(xa * 0.6366197723675814);

  3592.             // Compute remainder.
  3593.             double remA;
  3594.             double remB;
  3595.             while (true) {
  3596.                 double a = -k * 1.570796251296997;
  3597.                 remA = xa + a;
  3598.                 remB = -(remA - xa - a);

  3599.                 a = -k * 7.549789948768648E-8;
  3600.                 double b = remA;
  3601.                 remA = a + b;
  3602.                 remB += -(remA - b - a);

  3603.                 a = -k * 6.123233995736766E-17;
  3604.                 b = remA;
  3605.                 remA = a + b;
  3606.                 remB += -(remA - b - a);

  3607.                 if (remA > 0) {
  3608.                     break;
  3609.                 }

  3610.                 // Remainder is negative, so decrement k and try again.
  3611.                 // This should only happen if the input is very close
  3612.                 // to an even multiple of pi/2.
  3613.                 --k;
  3614.             }

  3615.             this.finalK = k;
  3616.             this.finalRemA = remA;
  3617.             this.finalRemB = remB;
  3618.         }

  3619.         /**
  3620.          * @return k
  3621.          */
  3622.         int getK() {
  3623.             return finalK;
  3624.         }
  3625.         /**
  3626.          * @return remA
  3627.          */
  3628.         double getRemA() {
  3629.             return finalRemA;
  3630.         }
  3631.         /**
  3632.          * @return remB
  3633.          */
  3634.         double getRemB() {
  3635.             return finalRemB;
  3636.         }
  3637.     }
  3638. }