View Javadoc

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.math.util;
18  
19  import java.io.PrintStream;
20  
21  /**
22   * Faster, more accurate, portable alternative to {@link Math} and
23   * {@link StrictMath} for large scale computation.
24   * <p>
25   * FastMath is a drop-in replacement for both Math and StrictMath. This
26   * means that for any method in Math (say {@code Math.sin(x)} or
27   * {@code Math.cbrt(y)}), user can directly change the class and use the
28   * methods as is (using {@code FastMath.sin(x)} or {@code FastMath.cbrt(y)}
29   * in the previous example).
30   * </p>
31   * <p>
32   * FastMath speed is achieved by relying heavily on optimizing compilers
33   * to native code present in many JVMs today and use of large tables.
34   * The larger tables are lazily initialised on first use, so that the setup
35   * time does not penalise methods that don't need them.
36   * </p>
37   * <p>
38   * Note that FastMath is
39   * extensively used inside Apache Commons Math, so by calling some algorithms,
40   * the overhead when the the tables need to be intialised will occur
41   * regardless of the end-user calling FastMath methods directly or not.
42   * Performance figures for a specific JVM and hardware can be evaluated by
43   * running the FastMathTestPerformance tests in the test directory of the source
44   * distribution.
45   * </p>
46   * <p>
47   * FastMath accuracy should be mostly independent of the JVM as it relies only
48   * on IEEE-754 basic operations and on embedded tables. Almost all operations
49   * are accurate to about 0.5 ulp throughout the domain range. This statement,
50   * of course is only a rough global observed behavior, it is <em>not</em> a
51   * guarantee for <em>every</em> double numbers input (see William Kahan's <a
52   * href="http://en.wikipedia.org/wiki/Rounding#The_table-maker.27s_dilemma">Table
53   * Maker's Dilemma</a>).
54   * </p>
55   * <p>
56   * FastMath additionally implements the following methods not found in Math/StrictMath:
57   * <ul>
58   * <li>{@link #asinh(double)}</li>
59   * <li>{@link #acosh(double)}</li>
60   * <li>{@link #atanh(double)}</li>
61   * </ul>
62   * The following methods are found in Math/StrictMath since 1.6 only, they are provided
63   * by FastMath even in 1.5 Java virtual machines
64   * <ul>
65   * <li>{@link #copySign(double, double)}</li>
66   * <li>{@link #getExponent(double)}</li>
67   * <li>{@link #nextAfter(double,double)}</li>
68   * <li>{@link #nextUp(double)}</li>
69   * <li>{@link #scalb(double, int)}</li>
70   * <li>{@link #copySign(float, float)}</li>
71   * <li>{@link #getExponent(float)}</li>
72   * <li>{@link #nextAfter(float,double)}</li>
73   * <li>{@link #nextUp(float)}</li>
74   * <li>{@link #scalb(float, int)}</li>
75   * </ul>
76   * </p>
77   * @version $Id: FastMath.java 1181175 2011-10-10 19:50:53Z erans $
78   * @since 2.2
79   */
80  public class FastMath {
81  
82      /** Archimede's constant PI, ratio of circle circumference to diameter. */
83      public static final double PI = 105414357.0 / 33554432.0 + 1.984187159361080883e-9;
84  
85      /** Napier's constant e, base of the natural logarithm. */
86      public static final double E = 2850325.0 / 1048576.0 + 8.254840070411028747e-8;
87  
88      /** Index of exp(0) in the array of integer exponentials. */
89      static final int EXP_INT_TABLE_MAX_INDEX = 750;
90      /** Length of the array of integer exponentials. */
91      static final int EXP_INT_TABLE_LEN = EXP_INT_TABLE_MAX_INDEX * 2;
92      /** Logarithm table length. */
93      static final int LN_MANT_LEN = 1024;
94      /** Exponential fractions table length. */
95      static final int EXP_FRAC_TABLE_LEN = 1025; // 0, 1/1024, ... 1024/1024
96  
97      /** Indicator for tables initialization.
98       * <p>
99       * This compile-time constant should be set to true only if one explicitly
100      * wants to compute the tables at class loading time instead of using the
101      * already computed ones provided as literal arrays below.
102      * </p>
103      */
104     private static final boolean RECOMPUTE_TABLES_AT_RUNTIME = false;
105     /** Indicator for loading big tables from "resource" files. */
106     private static final boolean LOAD_RESOURCES = false;
107 
108     /** log(2) (high bits). */
109     private static final double LN_2_A = 0.693147063255310059;
110 
111     /** log(2) (low bits). */
112     private static final double LN_2_B = 1.17304635250823482e-7;
113 
114     /** Coefficients for log, when input 0.99 < x < 1.01. */
115     private static final double LN_QUICK_COEF[][] = {
116         {1.0, 5.669184079525E-24},
117         {-0.25, -0.25},
118         {0.3333333134651184, 1.986821492305628E-8},
119         {-0.25, -6.663542893624021E-14},
120         {0.19999998807907104, 1.1921056801463227E-8},
121         {-0.1666666567325592, -7.800414592973399E-9},
122         {0.1428571343421936, 5.650007086920087E-9},
123         {-0.12502530217170715, -7.44321345601866E-11},
124         {0.11113807559013367, 9.219544613762692E-9},
125     };
126 
127     /** Coefficients for log in the range of 1.0 < x < 1.0 + 2^-10. */
128     private static final double LN_HI_PREC_COEF[][] = {
129         {1.0, -6.032174644509064E-23},
130         {-0.25, -0.25},
131         {0.3333333134651184, 1.9868161777724352E-8},
132         {-0.2499999701976776, -2.957007209750105E-8},
133         {0.19999954104423523, 1.5830993332061267E-10},
134         {-0.16624879837036133, -2.6033824355191673E-8}
135     };
136 
137     /** Sine, Cosine, Tangent tables are for 0, 1/8, 2/8, ... 13/8 = PI/2 approx. */
138     private static final int SINE_TABLE_LEN = 14;
139 
140     /** Sine table (high bits). */
141     private static final double SINE_TABLE_A[] =
142         {
143         +0.0d,
144         +0.1246747374534607d,
145         +0.24740394949913025d,
146         +0.366272509098053d,
147         +0.4794255495071411d,
148         +0.5850973129272461d,
149         +0.6816387176513672d,
150         +0.7675435543060303d,
151         +0.8414709568023682d,
152         +0.902267575263977d,
153         +0.9489846229553223d,
154         +0.9808930158615112d,
155         +0.9974949359893799d,
156         +0.9985313415527344d,
157     };
158 
159     /** Sine table (low bits). */
160     private static final double SINE_TABLE_B[] =
161         {
162         +0.0d,
163         -4.068233003401932E-9d,
164         +9.755392680573412E-9d,
165         +1.9987994582857286E-8d,
166         -1.0902938113007961E-8d,
167         -3.9986783938944604E-8d,
168         +4.23719669792332E-8d,
169         -5.207000323380292E-8d,
170         +2.800552834259E-8d,
171         +1.883511811213715E-8d,
172         -3.5997360512765566E-9d,
173         +4.116164446561962E-8d,
174         +5.0614674548127384E-8d,
175         -1.0129027912496858E-9d,
176     };
177 
178     /** Cosine table (high bits). */
179     private static final double COSINE_TABLE_A[] =
180         {
181         +1.0d,
182         +0.9921976327896118d,
183         +0.9689123630523682d,
184         +0.9305076599121094d,
185         +0.8775825500488281d,
186         +0.8109631538391113d,
187         +0.7316888570785522d,
188         +0.6409968137741089d,
189         +0.5403022766113281d,
190         +0.4311765432357788d,
191         +0.3153223395347595d,
192         +0.19454771280288696d,
193         +0.07073719799518585d,
194         -0.05417713522911072d,
195     };
196 
197     /** Cosine table (low bits). */
198     private static final double COSINE_TABLE_B[] =
199         {
200         +0.0d,
201         +3.4439717236742845E-8d,
202         +5.865827662008209E-8d,
203         -3.7999795083850525E-8d,
204         +1.184154459111628E-8d,
205         -3.43338934259355E-8d,
206         +1.1795268640216787E-8d,
207         +4.438921624363781E-8d,
208         +2.925681159240093E-8d,
209         -2.6437112632041807E-8d,
210         +2.2860509143963117E-8d,
211         -4.813899778443457E-9d,
212         +3.6725170580355583E-9d,
213         +2.0217439756338078E-10d,
214     };
215 
216 
217     /** Tangent table, used by atan() (high bits). */
218     private static final double TANGENT_TABLE_A[] =
219         {
220         +0.0d,
221         +0.1256551444530487d,
222         +0.25534194707870483d,
223         +0.3936265707015991d,
224         +0.5463024377822876d,
225         +0.7214844226837158d,
226         +0.9315965175628662d,
227         +1.1974215507507324d,
228         +1.5574076175689697d,
229         +2.092571258544922d,
230         +3.0095696449279785d,
231         +5.041914939880371d,
232         +14.101419448852539d,
233         -18.430862426757812d,
234     };
235 
236     /** Tangent table, used by atan() (low bits). */
237     private static final double TANGENT_TABLE_B[] =
238         {
239         +0.0d,
240         -7.877917738262007E-9d,
241         -2.5857668567479893E-8d,
242         +5.2240336371356666E-9d,
243         +5.206150291559893E-8d,
244         +1.8307188599677033E-8d,
245         -5.7618793749770706E-8d,
246         +7.848361555046424E-8d,
247         +1.0708593250394448E-7d,
248         +1.7827257129423813E-8d,
249         +2.893485277253286E-8d,
250         +3.1660099222737955E-7d,
251         +4.983191803254889E-7d,
252         -3.356118100840571E-7d,
253     };
254 
255     /** Bits of 1/(2*pi), need for reducePayneHanek(). */
256     private static final long RECIP_2PI[] = new long[] {
257         (0x28be60dbL << 32) | 0x9391054aL,
258         (0x7f09d5f4L << 32) | 0x7d4d3770L,
259         (0x36d8a566L << 32) | 0x4f10e410L,
260         (0x7f9458eaL << 32) | 0xf7aef158L,
261         (0x6dc91b8eL << 32) | 0x909374b8L,
262         (0x01924bbaL << 32) | 0x82746487L,
263         (0x3f877ac7L << 32) | 0x2c4a69cfL,
264         (0xba208d7dL << 32) | 0x4baed121L,
265         (0x3a671c09L << 32) | 0xad17df90L,
266         (0x4e64758eL << 32) | 0x60d4ce7dL,
267         (0x272117e2L << 32) | 0xef7e4a0eL,
268         (0xc7fe25ffL << 32) | 0xf7816603L,
269         (0xfbcbc462L << 32) | 0xd6829b47L,
270         (0xdb4d9fb3L << 32) | 0xc9f2c26dL,
271         (0xd3d18fd9L << 32) | 0xa797fa8bL,
272         (0x5d49eeb1L << 32) | 0xfaf97c5eL,
273         (0xcf41ce7dL << 32) | 0xe294a4baL,
274          0x9afed7ecL << 32  };
275 
276     /** Bits of pi/4, need for reducePayneHanek(). */
277     private static final long PI_O_4_BITS[] = new long[] {
278         (0xc90fdaa2L << 32) | 0x2168c234L,
279         (0xc4c6628bL << 32) | 0x80dc1cd1L };
280 
281     /** Eighths.
282      * This is used by sinQ, because its faster to do a table lookup than
283      * a multiply in this time-critical routine
284      */
285     private static final double EIGHTHS[] = {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};
286 
287     /** Table of 2^((n+2)/3) */
288     private static final double CBRTTWO[] = { 0.6299605249474366,
289                                             0.7937005259840998,
290                                             1.0,
291                                             1.2599210498948732,
292                                             1.5874010519681994 };
293 
294     /*
295      *  There are 52 bits in the mantissa of a double.
296      *  For additional precision, the code splits double numbers into two parts,
297      *  by clearing the low order 30 bits if possible, and then performs the arithmetic
298      *  on each half separately.
299      */
300 
301     /**
302      * 0x40000000 - used to split a double into two parts, both with the low order bits cleared.
303      * Equivalent to 2^30.
304      */
305     private static final long HEX_40000000 = 0x40000000L; // 1073741824L
306 
307     /** Mask used to clear low order 30 bits */
308     private static final long MASK_30BITS = -1L - (HEX_40000000 -1); // 0xFFFFFFFFC0000000L;
309 
310     /** 2^52 - double numbers this large must be integral (no fraction) or NaN or Infinite */
311     private static final double TWO_POWER_52 = 4503599627370496.0;
312 
313     /** Constant: {@value}. */
314     private static final double F_1_3 = 1d / 3d;
315     /** Constant: {@value}. */
316     private static final double F_1_5 = 1d / 5d;
317     /** Constant: {@value}. */
318     private static final double F_1_7 = 1d / 7d;
319     /** Constant: {@value}. */
320     private static final double F_1_9 = 1d / 9d;
321     /** Constant: {@value}. */
322     private static final double F_1_11 = 1d / 11d;
323     /** Constant: {@value}. */
324     private static final double F_1_13 = 1d / 13d;
325     /** Constant: {@value}. */
326     private static final double F_1_15 = 1d / 15d;
327     /** Constant: {@value}. */
328     private static final double F_1_17 = 1d / 17d;
329     /** Constant: {@value}. */
330     private static final double F_3_4 = 3d / 4d;
331     /** Constant: {@value}. */
332     private static final double F_15_16 = 15d / 16d;
333     /** Constant: {@value}. */
334     private static final double F_13_14 = 13d / 14d;
335     /** Constant: {@value}. */
336     private static final double F_11_12 = 11d / 12d;
337     /** Constant: {@value}. */
338     private static final double F_9_10 = 9d / 10d;
339     /** Constant: {@value}. */
340     private static final double F_7_8 = 7d / 8d;
341     /** Constant: {@value}. */
342     private static final double F_5_6 = 5d / 6d;
343     /** Constant: {@value}. */
344     private static final double F_1_2 = 1d / 2d;
345 
346     /**
347      * Private Constructor
348      */
349     private FastMath() {}
350 
351     // Generic helper methods
352 
353     /**
354      * Get the high order bits from the mantissa.
355      * Equivalent to adding and subtracting HEX_40000 but also works for very large numbers
356      *
357      * @param d the value to split
358      * @return the high order part of the mantissa
359      */
360     private static double doubleHighPart(double d) {
361         if (d > -MathUtils.SAFE_MIN && d < MathUtils.SAFE_MIN){
362             return d; // These are un-normalised - don't try to convert
363         }
364         long xl = Double.doubleToLongBits(d);
365         xl = xl & MASK_30BITS; // Drop low order bits
366         return Double.longBitsToDouble(xl);
367     }
368 
369     /** Compute the square root of a number.
370      * <p><b>Note:</b> this implementation currently delegates to {@link Math#sqrt}
371      * @param a number on which evaluation is done
372      * @return square root of a
373      */
374     public static double sqrt(final double a) {
375         return Math.sqrt(a);
376     }
377 
378     /** Compute the hyperbolic cosine of a number.
379      * @param x number on which evaluation is done
380      * @return hyperbolic cosine of x
381      */
382     public static double cosh(double x) {
383       if (x != x) {
384           return x;
385       }
386 
387       // cosh[z] = (exp(z) + exp(-z))/2
388 
389       // for numbers with magnitude 20 or so,
390       // exp(-z) can be ignored in comparison with exp(z)
391 
392       if (x > 20.0) {
393           return exp(x)/2.0;
394       }
395 
396       if (x < -20) {
397           return exp(-x)/2.0;
398       }
399 
400       double hiPrec[] = new double[2];
401       if (x < 0.0) {
402           x = -x;
403       }
404       exp(x, 0.0, hiPrec);
405 
406       double ya = hiPrec[0] + hiPrec[1];
407       double yb = -(ya - hiPrec[0] - hiPrec[1]);
408 
409       double temp = ya * HEX_40000000;
410       double yaa = ya + temp - temp;
411       double yab = ya - yaa;
412 
413       // recip = 1/y
414       double recip = 1.0/ya;
415       temp = recip * HEX_40000000;
416       double recipa = recip + temp - temp;
417       double recipb = recip - recipa;
418 
419       // Correct for rounding in division
420       recipb += (1.0 - yaa*recipa - yaa*recipb - yab*recipa - yab*recipb) * recip;
421       // Account for yb
422       recipb += -yb * recip * recip;
423 
424       // y = y + 1/y
425       temp = ya + recipa;
426       yb += -(temp - ya - recipa);
427       ya = temp;
428       temp = ya + recipb;
429       yb += -(temp - ya - recipb);
430       ya = temp;
431 
432       double result = ya + yb;
433       result *= 0.5;
434       return result;
435     }
436 
437     /** Compute the hyperbolic sine of a number.
438      * @param x number on which evaluation is done
439      * @return hyperbolic sine of x
440      */
441     public static double sinh(double x) {
442       boolean negate = false;
443       if (x != x) {
444           return x;
445       }
446 
447       // sinh[z] = (exp(z) - exp(-z) / 2
448 
449       // for values of z larger than about 20,
450       // exp(-z) can be ignored in comparison with exp(z)
451 
452       if (x > 20.0) {
453           return exp(x)/2.0;
454       }
455 
456       if (x < -20) {
457           return -exp(-x)/2.0;
458       }
459 
460       if (x == 0) {
461           return x;
462       }
463 
464       if (x < 0.0) {
465           x = -x;
466           negate = true;
467       }
468 
469       double result;
470 
471       if (x > 0.25) {
472           double hiPrec[] = new double[2];
473           exp(x, 0.0, hiPrec);
474 
475           double ya = hiPrec[0] + hiPrec[1];
476           double yb = -(ya - hiPrec[0] - hiPrec[1]);
477 
478           double temp = ya * HEX_40000000;
479           double yaa = ya + temp - temp;
480           double yab = ya - yaa;
481 
482           // recip = 1/y
483           double recip = 1.0/ya;
484           temp = recip * HEX_40000000;
485           double recipa = recip + temp - temp;
486           double recipb = recip - recipa;
487 
488           // Correct for rounding in division
489           recipb += (1.0 - yaa*recipa - yaa*recipb - yab*recipa - yab*recipb) * recip;
490           // Account for yb
491           recipb += -yb * recip * recip;
492 
493           recipa = -recipa;
494           recipb = -recipb;
495 
496           // y = y + 1/y
497           temp = ya + recipa;
498           yb += -(temp - ya - recipa);
499           ya = temp;
500           temp = ya + recipb;
501           yb += -(temp - ya - recipb);
502           ya = temp;
503 
504           result = ya + yb;
505           result *= 0.5;
506       }
507       else {
508           double hiPrec[] = new double[2];
509           expm1(x, hiPrec);
510 
511           double ya = hiPrec[0] + hiPrec[1];
512           double yb = -(ya - hiPrec[0] - hiPrec[1]);
513 
514           /* Compute expm1(-x) = -expm1(x) / (expm1(x) + 1) */
515           double denom = 1.0 + ya;
516           double denomr = 1.0 / denom;
517           double denomb = -(denom - 1.0 - ya) + yb;
518           double ratio = ya * denomr;
519           double temp = ratio * HEX_40000000;
520           double ra = ratio + temp - temp;
521           double rb = ratio - ra;
522 
523           temp = denom * HEX_40000000;
524           double za = denom + temp - temp;
525           double zb = denom - za;
526 
527           rb += (ya - za*ra - za*rb - zb*ra - zb*rb) * denomr;
528 
529           // Adjust for yb
530           rb += yb*denomr;                        // numerator
531           rb += -ya * denomb * denomr * denomr;   // denominator
532 
533           // y = y - 1/y
534           temp = ya + ra;
535           yb += -(temp - ya - ra);
536           ya = temp;
537           temp = ya + rb;
538           yb += -(temp - ya - rb);
539           ya = temp;
540 
541           result = ya + yb;
542           result *= 0.5;
543       }
544 
545       if (negate) {
546           result = -result;
547       }
548 
549       return result;
550     }
551 
552     /** Compute the hyperbolic tangent of a number.
553      * @param x number on which evaluation is done
554      * @return hyperbolic tangent of x
555      */
556     public static double tanh(double x) {
557       boolean negate = false;
558 
559       if (x != x) {
560           return x;
561       }
562 
563       // tanh[z] = sinh[z] / cosh[z]
564       // = (exp(z) - exp(-z)) / (exp(z) + exp(-z))
565       // = (exp(2x) - 1) / (exp(2x) + 1)
566 
567       // for magnitude > 20, sinh[z] == cosh[z] in double precision
568 
569       if (x > 20.0) {
570           return 1.0;
571       }
572 
573       if (x < -20) {
574           return -1.0;
575       }
576 
577       if (x == 0) {
578           return x;
579       }
580 
581       if (x < 0.0) {
582           x = -x;
583           negate = true;
584       }
585 
586       double result;
587       if (x >= 0.5) {
588           double hiPrec[] = new double[2];
589           // tanh(x) = (exp(2x) - 1) / (exp(2x) + 1)
590           exp(x*2.0, 0.0, hiPrec);
591 
592           double ya = hiPrec[0] + hiPrec[1];
593           double yb = -(ya - hiPrec[0] - hiPrec[1]);
594 
595           /* Numerator */
596           double na = -1.0 + ya;
597           double nb = -(na + 1.0 - ya);
598           double temp = na + yb;
599           nb += -(temp - na - yb);
600           na = temp;
601 
602           /* Denominator */
603           double da = 1.0 + ya;
604           double db = -(da - 1.0 - ya);
605           temp = da + yb;
606           db += -(temp - da - yb);
607           da = temp;
608 
609           temp = da * HEX_40000000;
610           double daa = da + temp - temp;
611           double dab = da - daa;
612 
613           // ratio = na/da
614           double ratio = na/da;
615           temp = ratio * HEX_40000000;
616           double ratioa = ratio + temp - temp;
617           double ratiob = ratio - ratioa;
618 
619           // Correct for rounding in division
620           ratiob += (na - daa*ratioa - daa*ratiob - dab*ratioa - dab*ratiob) / da;
621 
622           // Account for nb
623           ratiob += nb / da;
624           // Account for db
625           ratiob += -db * na / da / da;
626 
627           result = ratioa + ratiob;
628       }
629       else {
630           double hiPrec[] = new double[2];
631           // tanh(x) = expm1(2x) / (expm1(2x) + 2)
632           expm1(x*2.0, hiPrec);
633 
634           double ya = hiPrec[0] + hiPrec[1];
635           double yb = -(ya - hiPrec[0] - hiPrec[1]);
636 
637           /* Numerator */
638           double na = ya;
639           double nb = yb;
640 
641           /* Denominator */
642           double da = 2.0 + ya;
643           double db = -(da - 2.0 - ya);
644           double temp = da + yb;
645           db += -(temp - da - yb);
646           da = temp;
647 
648           temp = da * HEX_40000000;
649           double daa = da + temp - temp;
650           double dab = da - daa;
651 
652           // ratio = na/da
653           double ratio = na/da;
654           temp = ratio * HEX_40000000;
655           double ratioa = ratio + temp - temp;
656           double ratiob = ratio - ratioa;
657 
658           // Correct for rounding in division
659           ratiob += (na - daa*ratioa - daa*ratiob - dab*ratioa - dab*ratiob) / da;
660 
661           // Account for nb
662           ratiob += nb / da;
663           // Account for db
664           ratiob += -db * na / da / da;
665 
666           result = ratioa + ratiob;
667       }
668 
669       if (negate) {
670           result = -result;
671       }
672 
673       return result;
674     }
675 
676     /** Compute the inverse hyperbolic cosine of a number.
677      * @param a number on which evaluation is done
678      * @return inverse hyperbolic cosine of a
679      */
680     public static double acosh(final double a) {
681         return FastMath.log(a + FastMath.sqrt(a * a - 1));
682     }
683 
684     /** Compute the inverse hyperbolic sine of a number.
685      * @param a number on which evaluation is done
686      * @return inverse hyperbolic sine of a
687      */
688     public static double asinh(double a) {
689         boolean negative = false;
690         if (a < 0) {
691             negative = true;
692             a = -a;
693         }
694 
695         double absAsinh;
696         if (a > 0.167) {
697             absAsinh = FastMath.log(FastMath.sqrt(a * a + 1) + a);
698         } else {
699             final double a2 = a * a;
700             if (a > 0.097) {
701                 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);
702             } else if (a > 0.036) {
703                 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);
704             } else if (a > 0.0036) {
705                 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);
706             } else {
707                 absAsinh = a * (1 - a2 * (F_1_3 - a2 * F_1_5 * F_3_4) * F_1_2);
708             }
709         }
710 
711         return negative ? -absAsinh : absAsinh;
712     }
713 
714     /** Compute the inverse hyperbolic tangent of a number.
715      * @param a number on which evaluation is done
716      * @return inverse hyperbolic tangent of a
717      */
718     public static double atanh(double a) {
719         boolean negative = false;
720         if (a < 0) {
721             negative = true;
722             a = -a;
723         }
724 
725         double absAtanh;
726         if (a > 0.15) {
727             absAtanh = 0.5 * FastMath.log((1 + a) / (1 - a));
728         } else {
729             final double a2 = a * a;
730             if (a > 0.087) {
731                 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))))))));
732             } else if (a > 0.031) {
733                 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))))));
734             } else if (a > 0.003) {
735                 absAtanh = a * (1 + a2 * (F_1_3 + a2 * (F_1_5 + a2 * (F_1_7 + a2 * F_1_9))));
736             } else {
737                 absAtanh = a * (1 + a2 * (F_1_3 + a2 * F_1_5));
738             }
739         }
740 
741         return negative ? -absAtanh : absAtanh;
742     }
743 
744     /** Compute the signum of a number.
745      * The signum is -1 for negative numbers, +1 for positive numbers and 0 otherwise
746      * @param a number on which evaluation is done
747      * @return -1.0, -0.0, +0.0, +1.0 or NaN depending on sign of a
748      */
749     public static double signum(final double a) {
750         return (a < 0.0) ? -1.0 : ((a > 0.0) ? 1.0 : a); // return +0.0/-0.0/NaN depending on a
751     }
752 
753     /** Compute the signum of a number.
754      * The signum is -1 for negative numbers, +1 for positive numbers and 0 otherwise
755      * @param a number on which evaluation is done
756      * @return -1.0, -0.0, +0.0, +1.0 or NaN depending on sign of a
757      */
758     public static float signum(final float a) {
759         return (a < 0.0f) ? -1.0f : ((a > 0.0f) ? 1.0f : a); // return +0.0/-0.0/NaN depending on a
760     }
761 
762     /** Compute next number towards positive infinity.
763      * @param a number to which neighbor should be computed
764      * @return neighbor of a towards positive infinity
765      */
766     public static double nextUp(final double a) {
767         return nextAfter(a, Double.POSITIVE_INFINITY);
768     }
769 
770     /** Compute next number towards positive infinity.
771      * @param a number to which neighbor should be computed
772      * @return neighbor of a towards positive infinity
773      */
774     public static float nextUp(final float a) {
775         return nextAfter(a, Float.POSITIVE_INFINITY);
776     }
777 
778     /** Returns a pseudo-random number between 0.0 and 1.0.
779      * <p><b>Note:</b> this implementation currently delegates to {@link Math#random}
780      * @return a random number between 0.0 and 1.0
781      */
782     public static double random() {
783         return Math.random();
784     }
785 
786     /**
787      * Exponential function.
788      *
789      * Computes exp(x), function result is nearly rounded.   It will be correctly
790      * rounded to the theoretical value for 99.9% of input values, otherwise it will
791      * have a 1 UPL error.
792      *
793      * Method:
794      *    Lookup intVal = exp(int(x))
795      *    Lookup fracVal = exp(int(x-int(x) / 1024.0) * 1024.0 );
796      *    Compute z as the exponential of the remaining bits by a polynomial minus one
797      *    exp(x) = intVal * fracVal * (1 + z)
798      *
799      * Accuracy:
800      *    Calculation is done with 63 bits of precision, so result should be correctly
801      *    rounded for 99.9% of input values, with less than 1 ULP error otherwise.
802      *
803      * @param x   a double
804      * @return double e<sup>x</sup>
805      */
806     public static double exp(double x) {
807         return exp(x, 0.0, null);
808     }
809 
810     /**
811      * Internal helper method for exponential function.
812      * @param x original argument of the exponential function
813      * @param extra extra bits of precision on input (To Be Confirmed)
814      * @param hiPrec extra bits of precision on output (To Be Confirmed)
815      * @return exp(x)
816      */
817     private static double exp(double x, double extra, double[] hiPrec) {
818         double intPartA;
819         double intPartB;
820         int intVal;
821 
822         /* Lookup exp(floor(x)).
823          * intPartA will have the upper 22 bits, intPartB will have the lower
824          * 52 bits.
825          */
826         if (x < 0.0) {
827             intVal = (int) -x;
828 
829             if (intVal > 746) {
830                 if (hiPrec != null) {
831                     hiPrec[0] = 0.0;
832                     hiPrec[1] = 0.0;
833                 }
834                 return 0.0;
835             }
836 
837             if (intVal > 709) {
838                 /* This will produce a subnormal output */
839                 final double result = exp(x+40.19140625, extra, hiPrec) / 285040095144011776.0;
840                 if (hiPrec != null) {
841                     hiPrec[0] /= 285040095144011776.0;
842                     hiPrec[1] /= 285040095144011776.0;
843                 }
844                 return result;
845             }
846 
847             if (intVal == 709) {
848                 /* exp(1.494140625) is nearly a machine number... */
849                 final double result = exp(x+1.494140625, extra, hiPrec) / 4.455505956692756620;
850                 if (hiPrec != null) {
851                     hiPrec[0] /= 4.455505956692756620;
852                     hiPrec[1] /= 4.455505956692756620;
853                 }
854                 return result;
855             }
856 
857             intVal++;
858 
859             intPartA = ExpIntTable.EXP_INT_TABLE_A[EXP_INT_TABLE_MAX_INDEX-intVal];
860             intPartB = ExpIntTable.EXP_INT_TABLE_B[EXP_INT_TABLE_MAX_INDEX-intVal];
861 
862             intVal = -intVal;
863         } else {
864             intVal = (int) x;
865 
866             if (intVal > 709) {
867                 if (hiPrec != null) {
868                     hiPrec[0] = Double.POSITIVE_INFINITY;
869                     hiPrec[1] = 0.0;
870                 }
871                 return Double.POSITIVE_INFINITY;
872             }
873 
874             intPartA = ExpIntTable.EXP_INT_TABLE_A[EXP_INT_TABLE_MAX_INDEX+intVal];
875             intPartB = ExpIntTable.EXP_INT_TABLE_B[EXP_INT_TABLE_MAX_INDEX+intVal];
876         }
877 
878         /* Get the fractional part of x, find the greatest multiple of 2^-10 less than
879          * x and look up the exp function of it.
880          * fracPartA will have the upper 22 bits, fracPartB the lower 52 bits.
881          */
882         final int intFrac = (int) ((x - intVal) * 1024.0);
883         final double fracPartA = ExpFracTable.EXP_FRAC_TABLE_A[intFrac];
884         final double fracPartB = ExpFracTable.EXP_FRAC_TABLE_B[intFrac];
885 
886         /* epsilon is the difference in x from the nearest multiple of 2^-10.  It
887          * has a value in the range 0 <= epsilon < 2^-10.
888          * Do the subtraction from x as the last step to avoid possible loss of percison.
889          */
890         final double epsilon = x - (intVal + intFrac / 1024.0);
891 
892         /* Compute z = exp(epsilon) - 1.0 via a minimax polynomial.  z has
893        full double precision (52 bits).  Since z < 2^-10, we will have
894        62 bits of precision when combined with the contant 1.  This will be
895        used in the last addition below to get proper rounding. */
896 
897         /* Remez generated polynomial.  Converges on the interval [0, 2^-10], error
898        is less than 0.5 ULP */
899         double z = 0.04168701738764507;
900         z = z * epsilon + 0.1666666505023083;
901         z = z * epsilon + 0.5000000000042687;
902         z = z * epsilon + 1.0;
903         z = z * epsilon + -3.940510424527919E-20;
904 
905         /* Compute (intPartA+intPartB) * (fracPartA+fracPartB) by binomial
906        expansion.
907        tempA is exact since intPartA and intPartB only have 22 bits each.
908        tempB will have 52 bits of precision.
909          */
910         double tempA = intPartA * fracPartA;
911         double tempB = intPartA * fracPartB + intPartB * fracPartA + intPartB * fracPartB;
912 
913         /* Compute the result.  (1+z)(tempA+tempB).  Order of operations is
914        important.  For accuracy add by increasing size.  tempA is exact and
915        much larger than the others.  If there are extra bits specified from the
916        pow() function, use them. */
917         final double tempC = tempB + tempA;
918         final double result;
919         if (extra != 0.0) {
920             result = tempC*extra*z + tempC*extra + tempC*z + tempB + tempA;
921         } else {
922             result = tempC*z + tempB + tempA;
923         }
924 
925         if (hiPrec != null) {
926             // If requesting high precision
927             hiPrec[0] = tempA;
928             hiPrec[1] = tempC*extra*z + tempC*extra + tempC*z + tempB;
929         }
930 
931         return result;
932     }
933 
934     /** Compute exp(x) - 1
935      * @param x number to compute shifted exponential
936      * @return exp(x) - 1
937      */
938     public static double expm1(double x) {
939       return expm1(x, null);
940     }
941 
942     /** Internal helper method for expm1
943      * @param x number to compute shifted exponential
944      * @param hiPrecOut receive high precision result for -1.0 < x < 1.0
945      * @return exp(x) - 1
946      */
947     private static double expm1(double x, double hiPrecOut[]) {
948         if (x != x || x == 0.0) { // NaN or zero
949             return x;
950         }
951 
952         if (x <= -1.0 || x >= 1.0) {
953             // If not between +/- 1.0
954             //return exp(x) - 1.0;
955             double hiPrec[] = new double[2];
956             exp(x, 0.0, hiPrec);
957             if (x > 0.0) {
958                 return -1.0 + hiPrec[0] + hiPrec[1];
959             } else {
960                 final double ra = -1.0 + hiPrec[0];
961                 double rb = -(ra + 1.0 - hiPrec[0]);
962                 rb += hiPrec[1];
963                 return ra + rb;
964             }
965         }
966 
967         double baseA;
968         double baseB;
969         double epsilon;
970         boolean negative = false;
971 
972         if (x < 0.0) {
973             x = -x;
974             negative = true;
975         }
976 
977         {
978             int intFrac = (int) (x * 1024.0);
979             double tempA = ExpFracTable.EXP_FRAC_TABLE_A[intFrac] - 1.0;
980             double tempB = ExpFracTable.EXP_FRAC_TABLE_B[intFrac];
981 
982             double temp = tempA + tempB;
983             tempB = -(temp - tempA - tempB);
984             tempA = temp;
985 
986             temp = tempA * HEX_40000000;
987             baseA = tempA + temp - temp;
988             baseB = tempB + (tempA - baseA);
989 
990             epsilon = x - intFrac/1024.0;
991         }
992 
993 
994         /* Compute expm1(epsilon) */
995         double zb = 0.008336750013465571;
996         zb = zb * epsilon + 0.041666663879186654;
997         zb = zb * epsilon + 0.16666666666745392;
998         zb = zb * epsilon + 0.49999999999999994;
999         zb = zb * epsilon;
1000         zb = zb * epsilon;
1001 
1002         double za = epsilon;
1003         double temp = za + zb;
1004         zb = -(temp - za - zb);
1005         za = temp;
1006 
1007         temp = za * HEX_40000000;
1008         temp = za + temp - temp;
1009         zb += za - temp;
1010         za = temp;
1011 
1012         /* Combine the parts.   expm1(a+b) = expm1(a) + expm1(b) + expm1(a)*expm1(b) */
1013         double ya = za * baseA;
1014         //double yb = za*baseB + zb*baseA + zb*baseB;
1015         temp = ya + za * baseB;
1016         double yb = -(temp - ya - za * baseB);
1017         ya = temp;
1018 
1019         temp = ya + zb * baseA;
1020         yb += -(temp - ya - zb * baseA);
1021         ya = temp;
1022 
1023         temp = ya + zb * baseB;
1024         yb += -(temp - ya - zb*baseB);
1025         ya = temp;
1026 
1027         //ya = ya + za + baseA;
1028         //yb = yb + zb + baseB;
1029         temp = ya + baseA;
1030         yb += -(temp - baseA - ya);
1031         ya = temp;
1032 
1033         temp = ya + za;
1034         //yb += (ya > za) ? -(temp - ya - za) : -(temp - za - ya);
1035         yb += -(temp - ya - za);
1036         ya = temp;
1037 
1038         temp = ya + baseB;
1039         //yb += (ya > baseB) ? -(temp - ya - baseB) : -(temp - baseB - ya);
1040         yb += -(temp - ya - baseB);
1041         ya = temp;
1042 
1043         temp = ya + zb;
1044         //yb += (ya > zb) ? -(temp - ya - zb) : -(temp - zb - ya);
1045         yb += -(temp - ya - zb);
1046         ya = temp;
1047 
1048         if (negative) {
1049             /* Compute expm1(-x) = -expm1(x) / (expm1(x) + 1) */
1050             double denom = 1.0 + ya;
1051             double denomr = 1.0 / denom;
1052             double denomb = -(denom - 1.0 - ya) + yb;
1053             double ratio = ya * denomr;
1054             temp = ratio * HEX_40000000;
1055             final double ra = ratio + temp - temp;
1056             double rb = ratio - ra;
1057 
1058             temp = denom * HEX_40000000;
1059             za = denom + temp - temp;
1060             zb = denom - za;
1061 
1062             rb += (ya - za * ra - za * rb - zb * ra - zb * rb) * denomr;
1063 
1064             // f(x) = x/1+x
1065             // Compute f'(x)
1066             // Product rule:  d(uv) = du*v + u*dv
1067             // Chain rule:  d(f(g(x)) = f'(g(x))*f(g'(x))
1068             // d(1/x) = -1/(x*x)
1069             // d(1/1+x) = -1/( (1+x)^2) *  1 =  -1/((1+x)*(1+x))
1070             // d(x/1+x) = -x/((1+x)(1+x)) + 1/1+x = 1 / ((1+x)(1+x))
1071 
1072             // Adjust for yb
1073             rb += yb * denomr;                      // numerator
1074             rb += -ya * denomb * denomr * denomr;   // denominator
1075 
1076             // negate
1077             ya = -ra;
1078             yb = -rb;
1079         }
1080 
1081         if (hiPrecOut != null) {
1082             hiPrecOut[0] = ya;
1083             hiPrecOut[1] = yb;
1084         }
1085 
1086         return ya + yb;
1087     }
1088 
1089     /**
1090      * Natural logarithm.
1091      *
1092      * @param x   a double
1093      * @return log(x)
1094      */
1095     public static double log(final double x) {
1096         return log(x, null);
1097     }
1098 
1099     /**
1100      * Internal helper method for natural logarithm function.
1101      * @param x original argument of the natural logarithm function
1102      * @param hiPrec extra bits of precision on output (To Be Confirmed)
1103      * @return log(x)
1104      */
1105     private static double log(final double x, final double[] hiPrec) {
1106         if (x==0) { // Handle special case of +0/-0
1107             return Double.NEGATIVE_INFINITY;
1108         }
1109         long bits = Double.doubleToLongBits(x);
1110 
1111         /* Handle special cases of negative input, and NaN */
1112         if ((bits & 0x8000000000000000L) != 0 || x != x) {
1113             if (x != 0.0) {
1114                 if (hiPrec != null) {
1115                     hiPrec[0] = Double.NaN;
1116                 }
1117 
1118                 return Double.NaN;
1119             }
1120         }
1121 
1122         /* Handle special cases of Positive infinity. */
1123         if (x == Double.POSITIVE_INFINITY) {
1124             if (hiPrec != null) {
1125                 hiPrec[0] = Double.POSITIVE_INFINITY;
1126             }
1127 
1128             return Double.POSITIVE_INFINITY;
1129         }
1130 
1131         /* Extract the exponent */
1132         int exp = (int)(bits >> 52)-1023;
1133 
1134         if ((bits & 0x7ff0000000000000L) == 0) {
1135             // Subnormal!
1136             if (x == 0) {
1137                 // Zero
1138                 if (hiPrec != null) {
1139                     hiPrec[0] = Double.NEGATIVE_INFINITY;
1140                 }
1141 
1142                 return Double.NEGATIVE_INFINITY;
1143             }
1144 
1145             /* Normalize the subnormal number. */
1146             bits <<= 1;
1147             while ( (bits & 0x0010000000000000L) == 0) {
1148                 exp--;
1149                 bits <<= 1;
1150             }
1151         }
1152 
1153 
1154         if (exp == -1 || exp == 0) {
1155             if (x < 1.01 && x > 0.99 && hiPrec == null) {
1156                 /* The normal method doesn't work well in the range [0.99, 1.01], so call do a straight
1157            polynomial expansion in higer precision. */
1158 
1159                /* Compute x - 1.0 and split it */
1160                 double xa = x - 1.0;
1161                 double xb = xa - x + 1.0;
1162                 double tmp = xa * HEX_40000000;
1163                 double aa = xa + tmp - tmp;
1164                 double ab = xa - aa;
1165                 xa = aa;
1166                 xb = ab;
1167 
1168                 double ya = LN_QUICK_COEF[LN_QUICK_COEF.length-1][0];
1169                 double yb = LN_QUICK_COEF[LN_QUICK_COEF.length-1][1];
1170 
1171                 for (int i = LN_QUICK_COEF.length - 2; i >= 0; i--) {
1172                     /* Multiply a = y * x */
1173                     aa = ya * xa;
1174                     ab = ya * xb + yb * xa + yb * xb;
1175                     /* split, so now y = a */
1176                     tmp = aa * HEX_40000000;
1177                     ya = aa + tmp - tmp;
1178                     yb = aa - ya + ab;
1179 
1180                     /* Add  a = y + lnQuickCoef */
1181                     aa = ya + LN_QUICK_COEF[i][0];
1182                     ab = yb + LN_QUICK_COEF[i][1];
1183                     /* Split y = a */
1184                     tmp = aa * HEX_40000000;
1185                     ya = aa + tmp - tmp;
1186                     yb = aa - ya + ab;
1187                 }
1188 
1189                 /* Multiply a = y * x */
1190                 aa = ya * xa;
1191                 ab = ya * xb + yb * xa + yb * xb;
1192                 /* split, so now y = a */
1193                 tmp = aa * HEX_40000000;
1194                 ya = aa + tmp - tmp;
1195                 yb = aa - ya + ab;
1196 
1197                 return ya + yb;
1198             }
1199         }
1200 
1201         // lnm is a log of a number in the range of 1.0 - 2.0, so 0 <= lnm < ln(2)
1202         double lnm[] = lnMant.LN_MANT[(int)((bits & 0x000ffc0000000000L) >> 42)];
1203 
1204         /*
1205     double epsilon = x / Double.longBitsToDouble(bits & 0xfffffc0000000000L);
1206 
1207     epsilon -= 1.0;
1208          */
1209 
1210         // y is the most significant 10 bits of the mantissa
1211         //double y = Double.longBitsToDouble(bits & 0xfffffc0000000000L);
1212         //double epsilon = (x - y) / y;
1213         double epsilon = (bits & 0x3ffffffffffL) / (TWO_POWER_52 + (bits & 0x000ffc0000000000L));
1214 
1215         double lnza = 0.0;
1216         double lnzb = 0.0;
1217 
1218         if (hiPrec != null) {
1219             /* split epsilon -> x */
1220             double tmp = epsilon * HEX_40000000;
1221             double aa = epsilon + tmp - tmp;
1222             double ab = epsilon - aa;
1223             double xa = aa;
1224             double xb = ab;
1225 
1226             /* Need a more accurate epsilon, so adjust the division. */
1227             double numer = bits & 0x3ffffffffffL;
1228             double denom = TWO_POWER_52 + (bits & 0x000ffc0000000000L);
1229             aa = numer - xa*denom - xb * denom;
1230             xb += aa / denom;
1231 
1232             /* Remez polynomial evaluation */
1233             double ya = LN_HI_PREC_COEF[LN_HI_PREC_COEF.length-1][0];
1234             double yb = LN_HI_PREC_COEF[LN_HI_PREC_COEF.length-1][1];
1235 
1236             for (int i = LN_HI_PREC_COEF.length - 2; i >= 0; i--) {
1237                 /* Multiply a = y * x */
1238                 aa = ya * xa;
1239                 ab = ya * xb + yb * xa + yb * xb;
1240                 /* split, so now y = a */
1241                 tmp = aa * HEX_40000000;
1242                 ya = aa + tmp - tmp;
1243                 yb = aa - ya + ab;
1244 
1245                 /* Add  a = y + lnHiPrecCoef */
1246                 aa = ya + LN_HI_PREC_COEF[i][0];
1247                 ab = yb + LN_HI_PREC_COEF[i][1];
1248                 /* Split y = a */
1249                 tmp = aa * HEX_40000000;
1250                 ya = aa + tmp - tmp;
1251                 yb = aa - ya + ab;
1252             }
1253 
1254             /* Multiply a = y * x */
1255             aa = ya * xa;
1256             ab = ya * xb + yb * xa + yb * xb;
1257 
1258             /* split, so now lnz = a */
1259             /*
1260       tmp = aa * 1073741824.0;
1261       lnza = aa + tmp - tmp;
1262       lnzb = aa - lnza + ab;
1263              */
1264             lnza = aa + ab;
1265             lnzb = -(lnza - aa - ab);
1266         } else {
1267             /* High precision not required.  Eval Remez polynomial
1268          using standard double precision */
1269             lnza = -0.16624882440418567;
1270             lnza = lnza * epsilon + 0.19999954120254515;
1271             lnza = lnza * epsilon + -0.2499999997677497;
1272             lnza = lnza * epsilon + 0.3333333333332802;
1273             lnza = lnza * epsilon + -0.5;
1274             lnza = lnza * epsilon + 1.0;
1275             lnza = lnza * epsilon;
1276         }
1277 
1278         /* Relative sizes:
1279          * lnzb     [0, 2.33E-10]
1280          * lnm[1]   [0, 1.17E-7]
1281          * ln2B*exp [0, 1.12E-4]
1282          * lnza      [0, 9.7E-4]
1283          * lnm[0]   [0, 0.692]
1284          * ln2A*exp [0, 709]
1285          */
1286 
1287         /* Compute the following sum:
1288          * lnzb + lnm[1] + ln2B*exp + lnza + lnm[0] + ln2A*exp;
1289          */
1290 
1291         //return lnzb + lnm[1] + ln2B*exp + lnza + lnm[0] + ln2A*exp;
1292         double a = LN_2_A*exp;
1293         double b = 0.0;
1294         double c = a+lnm[0];
1295         double d = -(c-a-lnm[0]);
1296         a = c;
1297         b = b + d;
1298 
1299         c = a + lnza;
1300         d = -(c - a - lnza);
1301         a = c;
1302         b = b + d;
1303 
1304         c = a + LN_2_B*exp;
1305         d = -(c - a - LN_2_B*exp);
1306         a = c;
1307         b = b + d;
1308 
1309         c = a + lnm[1];
1310         d = -(c - a - lnm[1]);
1311         a = c;
1312         b = b + d;
1313 
1314         c = a + lnzb;
1315         d = -(c - a - lnzb);
1316         a = c;
1317         b = b + d;
1318 
1319         if (hiPrec != null) {
1320             hiPrec[0] = a;
1321             hiPrec[1] = b;
1322         }
1323 
1324         return a + b;
1325     }
1326 
1327     /** Compute log(1 + x).
1328      * @param x a number
1329      * @return log(1 + x)
1330      */
1331     public static double log1p(final double x) {
1332 
1333         if (x == -1) {
1334             return x/0.0;   // -Infinity
1335         }
1336 
1337         if (x > 0 && 1/x == 0) { // x = Infinity
1338             return x;
1339         }
1340 
1341         if (x>1e-6 || x<-1e-6) {
1342             double xpa = 1.0 + x;
1343             double xpb = -(xpa - 1.0 - x);
1344 
1345             double hiPrec[] = new double[2];
1346 
1347             final double lores = log(xpa, hiPrec);
1348             if (Double.isInfinite(lores)){ // don't allow this to be converted to NaN
1349                 return lores;
1350             }
1351 
1352             /* Do a taylor series expansion around xpa */
1353             /* f(x+y) = f(x) + f'(x)*y + f''(x)/2 y^2 */
1354             double fx1 = xpb/xpa;
1355 
1356             double epsilon = 0.5 * fx1 + 1.0;
1357             epsilon = epsilon * fx1;
1358 
1359             return epsilon + hiPrec[1] + hiPrec[0];
1360         }
1361 
1362         /* Value is small |x| < 1e6, do a Taylor series centered on 1.0 */
1363         double y = x * F_1_3 - F_1_2;
1364         y = y * x + 1.0;
1365         y = y * x;
1366 
1367         return y;
1368     }
1369 
1370     /** Compute the base 10 logarithm.
1371      * @param x a number
1372      * @return log10(x)
1373      */
1374     public static double log10(final double x) {
1375         final double hiPrec[] = new double[2];
1376 
1377         final double lores = log(x, hiPrec);
1378         if (Double.isInfinite(lores)){ // don't allow this to be converted to NaN
1379             return lores;
1380         }
1381 
1382         final double tmp = hiPrec[0] * HEX_40000000;
1383         final double lna = hiPrec[0] + tmp - tmp;
1384         final double lnb = hiPrec[0] - lna + hiPrec[1];
1385 
1386         final double rln10a = 0.4342944622039795;
1387         final double rln10b = 1.9699272335463627E-8;
1388 
1389         return rln10b * lnb + rln10b * lna + rln10a * lnb + rln10a * lna;
1390     }
1391 
1392     /**
1393      * Power function.  Compute x^y.
1394      *
1395      * @param x   a double
1396      * @param y   a double
1397      * @return double
1398      */
1399     public static double pow(double x, double y) {
1400         final double lns[] = new double[2];
1401 
1402         if (y == 0.0) {
1403             return 1.0;
1404         }
1405 
1406         if (x != x) { // X is NaN
1407             return x;
1408         }
1409 
1410 
1411         if (x == 0) {
1412             long bits = Double.doubleToLongBits(x);
1413             if ((bits & 0x8000000000000000L) != 0) {
1414                 // -zero
1415                 long yi = (long) y;
1416 
1417                 if (y < 0 && y == yi && (yi & 1) == 1) {
1418                     return Double.NEGATIVE_INFINITY;
1419                 }
1420 
1421                 if (y > 0 && y == yi && (yi & 1) == 1) {
1422                     return -0.0;
1423                 }
1424             }
1425 
1426             if (y < 0) {
1427                 return Double.POSITIVE_INFINITY;
1428             }
1429             if (y > 0) {
1430                 return 0.0;
1431             }
1432 
1433             return Double.NaN;
1434         }
1435 
1436         if (x == Double.POSITIVE_INFINITY) {
1437             if (y != y) { // y is NaN
1438                 return y;
1439             }
1440             if (y < 0.0) {
1441                 return 0.0;
1442             } else {
1443                 return Double.POSITIVE_INFINITY;
1444             }
1445         }
1446 
1447         if (y == Double.POSITIVE_INFINITY) {
1448             if (x * x == 1.0) {
1449                 return Double.NaN;
1450             }
1451 
1452             if (x * x > 1.0) {
1453                 return Double.POSITIVE_INFINITY;
1454             } else {
1455                 return 0.0;
1456             }
1457         }
1458 
1459         if (x == Double.NEGATIVE_INFINITY) {
1460             if (y != y) { // y is NaN
1461                 return y;
1462             }
1463 
1464             if (y < 0) {
1465                 long yi = (long) y;
1466                 if (y == yi && (yi & 1) == 1) {
1467                     return -0.0;
1468                 }
1469 
1470                 return 0.0;
1471             }
1472 
1473             if (y > 0)  {
1474                 long yi = (long) y;
1475                 if (y == yi && (yi & 1) == 1) {
1476                     return Double.NEGATIVE_INFINITY;
1477                 }
1478 
1479                 return Double.POSITIVE_INFINITY;
1480             }
1481         }
1482 
1483         if (y == Double.NEGATIVE_INFINITY) {
1484 
1485             if (x * x == 1.0) {
1486                 return Double.NaN;
1487             }
1488 
1489             if (x * x < 1.0) {
1490                 return Double.POSITIVE_INFINITY;
1491             } else {
1492                 return 0.0;
1493             }
1494         }
1495 
1496         /* Handle special case x<0 */
1497         if (x < 0) {
1498             // y is an even integer in this case
1499             if (y >= TWO_POWER_52 || y <= -TWO_POWER_52) {
1500                 return pow(-x, y);
1501             }
1502 
1503             if (y == (long) y) {
1504                 // If y is an integer
1505                 return ((long)y & 1) == 0 ? pow(-x, y) : -pow(-x, y);
1506             } else {
1507                 return Double.NaN;
1508             }
1509         }
1510 
1511         /* Split y into ya and yb such that y = ya+yb */
1512         double ya;
1513         double yb;
1514         if (y < 8e298 && y > -8e298) {
1515             double tmp1 = y * HEX_40000000;
1516             ya = y + tmp1 - tmp1;
1517             yb = y - ya;
1518         } else {
1519             double tmp1 = y * 9.31322574615478515625E-10;
1520             double tmp2 = tmp1 * 9.31322574615478515625E-10;
1521             ya = (tmp1 + tmp2 - tmp1) * HEX_40000000 * HEX_40000000;
1522             yb = y - ya;
1523         }
1524 
1525         /* Compute ln(x) */
1526         final double lores = log(x, lns);
1527         if (Double.isInfinite(lores)){ // don't allow this to be converted to NaN
1528             return lores;
1529         }
1530 
1531         double lna = lns[0];
1532         double lnb = lns[1];
1533 
1534         /* resplit lns */
1535         double tmp1 = lna * HEX_40000000;
1536         double tmp2 = lna + tmp1 - tmp1;
1537         lnb += lna - tmp2;
1538         lna = tmp2;
1539 
1540         // y*ln(x) = (aa+ab)
1541         final double aa = lna * ya;
1542         final double ab = lna * yb + lnb * ya + lnb * yb;
1543 
1544         lna = aa+ab;
1545         lnb = -(lna - aa - ab);
1546 
1547         double z = 1.0 / 120.0;
1548         z = z * lnb + (1.0 / 24.0);
1549         z = z * lnb + (1.0 / 6.0);
1550         z = z * lnb + 0.5;
1551         z = z * lnb + 1.0;
1552         z = z * lnb;
1553 
1554         final double result = exp(lna, z, null);
1555         //result = result + result * z;
1556         return result;
1557     }
1558 
1559 
1560     /**
1561      *  Computes sin(x) - x, where |x| < 1/16.
1562      *  Use a Remez polynomial approximation.
1563      *  @param x a number smaller than 1/16
1564      *  @return sin(x) - x
1565      */
1566     private static double polySine(final double x)
1567     {
1568         double x2 = x*x;
1569 
1570         double p = 2.7553817452272217E-6;
1571         p = p * x2 + -1.9841269659586505E-4;
1572         p = p * x2 + 0.008333333333329196;
1573         p = p * x2 + -0.16666666666666666;
1574         //p *= x2;
1575         //p *= x;
1576         p = p * x2 * x;
1577 
1578         return p;
1579     }
1580 
1581     /**
1582      *  Computes cos(x) - 1, where |x| < 1/16.
1583      *  Use a Remez polynomial approximation.
1584      *  @param x a number smaller than 1/16
1585      *  @return cos(x) - 1
1586      */
1587     private static double polyCosine(double x) {
1588         double x2 = x*x;
1589 
1590         double p = 2.479773539153719E-5;
1591         p = p * x2 + -0.0013888888689039883;
1592         p = p * x2 + 0.041666666666621166;
1593         p = p * x2 + -0.49999999999999994;
1594         p *= x2;
1595 
1596         return p;
1597     }
1598 
1599     /**
1600      *  Compute sine over the first quadrant (0 < x < pi/2).
1601      *  Use combination of table lookup and rational polynomial expansion.
1602      *  @param xa number from which sine is requested
1603      *  @param xb extra bits for x (may be 0.0)
1604      *  @return sin(xa + xb)
1605      */
1606     private static double sinQ(double xa, double xb) {
1607         int idx = (int) ((xa * 8.0) + 0.5);
1608         final double epsilon = xa - EIGHTHS[idx]; //idx*0.125;
1609 
1610         // Table lookups
1611         final double sintA = SINE_TABLE_A[idx];
1612         final double sintB = SINE_TABLE_B[idx];
1613         final double costA = COSINE_TABLE_A[idx];
1614         final double costB = COSINE_TABLE_B[idx];
1615 
1616         // Polynomial eval of sin(epsilon), cos(epsilon)
1617         double sinEpsA = epsilon;
1618         double sinEpsB = polySine(epsilon);
1619         final double cosEpsA = 1.0;
1620         final double cosEpsB = polyCosine(epsilon);
1621 
1622         // Split epsilon   xa + xb = x
1623         final double temp = sinEpsA * HEX_40000000;
1624         double temp2 = (sinEpsA + temp) - temp;
1625         sinEpsB +=  sinEpsA - temp2;
1626         sinEpsA = temp2;
1627 
1628         /* Compute sin(x) by angle addition formula */
1629         double result;
1630 
1631         /* Compute the following sum:
1632          *
1633          * result = sintA + costA*sinEpsA + sintA*cosEpsB + costA*sinEpsB +
1634          *          sintB + costB*sinEpsA + sintB*cosEpsB + costB*sinEpsB;
1635          *
1636          * Ranges of elements
1637          *
1638          * xxxtA   0            PI/2
1639          * xxxtB   -1.5e-9      1.5e-9
1640          * sinEpsA -0.0625      0.0625
1641          * sinEpsB -6e-11       6e-11
1642          * cosEpsA  1.0
1643          * cosEpsB  0           -0.0625
1644          *
1645          */
1646 
1647         //result = sintA + costA*sinEpsA + sintA*cosEpsB + costA*sinEpsB +
1648         //          sintB + costB*sinEpsA + sintB*cosEpsB + costB*sinEpsB;
1649 
1650         //result = sintA + sintA*cosEpsB + sintB + sintB * cosEpsB;
1651         //result += costA*sinEpsA + costA*sinEpsB + costB*sinEpsA + costB * sinEpsB;
1652         double a = 0;
1653         double b = 0;
1654 
1655         double t = sintA;
1656         double c = a + t;
1657         double d = -(c - a - t);
1658         a = c;
1659         b = b + d;
1660 
1661         t = costA * sinEpsA;
1662         c = a + t;
1663         d = -(c - a - t);
1664         a = c;
1665         b = b + d;
1666 
1667         b = b + sintA * cosEpsB + costA * sinEpsB;
1668         /*
1669     t = sintA*cosEpsB;
1670     c = a + t;
1671     d = -(c - a - t);
1672     a = c;
1673     b = b + d;
1674 
1675     t = costA*sinEpsB;
1676     c = a + t;
1677     d = -(c - a - t);
1678     a = c;
1679     b = b + d;
1680          */
1681 
1682         b = b + sintB + costB * sinEpsA + sintB * cosEpsB + costB * sinEpsB;
1683         /*
1684     t = sintB;
1685     c = a + t;
1686     d = -(c - a - t);
1687     a = c;
1688     b = b + d;
1689 
1690     t = costB*sinEpsA;
1691     c = a + t;
1692     d = -(c - a - t);
1693     a = c;
1694     b = b + d;
1695 
1696     t = sintB*cosEpsB;
1697     c = a + t;
1698     d = -(c - a - t);
1699     a = c;
1700     b = b + d;
1701 
1702     t = costB*sinEpsB;
1703     c = a + t;
1704     d = -(c - a - t);
1705     a = c;
1706     b = b + d;
1707          */
1708 
1709         if (xb != 0.0) {
1710             t = ((costA + costB) * (cosEpsA + cosEpsB) -
1711                  (sintA + sintB) * (sinEpsA + sinEpsB)) * xb;  // approximate cosine*xb
1712             c = a + t;
1713             d = -(c - a - t);
1714             a = c;
1715             b = b + d;
1716         }
1717 
1718         result = a + b;
1719 
1720         return result;
1721     }
1722 
1723     /**
1724      * Compute cosine in the first quadrant by subtracting input from PI/2 and
1725      * then calling sinQ.  This is more accurate as the input approaches PI/2.
1726      *  @param xa number from which cosine is requested
1727      *  @param xb extra bits for x (may be 0.0)
1728      *  @return cos(xa + xb)
1729      */
1730     private static double cosQ(double xa, double xb) {
1731         final double pi2a = 1.5707963267948966;
1732         final double pi2b = 6.123233995736766E-17;
1733 
1734         final double a = pi2a - xa;
1735         double b = -(a - pi2a + xa);
1736         b += pi2b - xb;
1737 
1738         return sinQ(a, b);
1739     }
1740 
1741     /**
1742      *  Compute tangent (or cotangent) over the first quadrant.   0 < x < pi/2
1743      *  Use combination of table lookup and rational polynomial expansion.
1744      *  @param xa number from which sine is requested
1745      *  @param xb extra bits for x (may be 0.0)
1746      *  @param cotanFlag if true, compute the cotangent instead of the tangent
1747      *  @return tan(xa+xb) (or cotangent, depending on cotanFlag)
1748      */
1749     private static double tanQ(double xa, double xb, boolean cotanFlag) {
1750 
1751         int idx = (int) ((xa * 8.0) + 0.5);
1752         final double epsilon = xa - EIGHTHS[idx]; //idx*0.125;
1753 
1754         // Table lookups
1755         final double sintA = SINE_TABLE_A[idx];
1756         final double sintB = SINE_TABLE_B[idx];
1757         final double costA = COSINE_TABLE_A[idx];
1758         final double costB = COSINE_TABLE_B[idx];
1759 
1760         // Polynomial eval of sin(epsilon), cos(epsilon)
1761         double sinEpsA = epsilon;
1762         double sinEpsB = polySine(epsilon);
1763         final double cosEpsA = 1.0;
1764         final double cosEpsB = polyCosine(epsilon);
1765 
1766         // Split epsilon   xa + xb = x
1767         double temp = sinEpsA * HEX_40000000;
1768         double temp2 = (sinEpsA + temp) - temp;
1769         sinEpsB +=  sinEpsA - temp2;
1770         sinEpsA = temp2;
1771 
1772         /* Compute sin(x) by angle addition formula */
1773 
1774         /* Compute the following sum:
1775          *
1776          * result = sintA + costA*sinEpsA + sintA*cosEpsB + costA*sinEpsB +
1777          *          sintB + costB*sinEpsA + sintB*cosEpsB + costB*sinEpsB;
1778          *
1779          * Ranges of elements
1780          *
1781          * xxxtA   0            PI/2
1782          * xxxtB   -1.5e-9      1.5e-9
1783          * sinEpsA -0.0625      0.0625
1784          * sinEpsB -6e-11       6e-11
1785          * cosEpsA  1.0
1786          * cosEpsB  0           -0.0625
1787          *
1788          */
1789 
1790         //result = sintA + costA*sinEpsA + sintA*cosEpsB + costA*sinEpsB +
1791         //          sintB + costB*sinEpsA + sintB*cosEpsB + costB*sinEpsB;
1792 
1793         //result = sintA + sintA*cosEpsB + sintB + sintB * cosEpsB;
1794         //result += costA*sinEpsA + costA*sinEpsB + costB*sinEpsA + costB * sinEpsB;
1795         double a = 0;
1796         double b = 0;
1797 
1798         // Compute sine
1799         double t = sintA;
1800         double c = a + t;
1801         double d = -(c - a - t);
1802         a = c;
1803         b = b + d;
1804 
1805         t = costA*sinEpsA;
1806         c = a + t;
1807         d = -(c - a - t);
1808         a = c;
1809         b = b + d;
1810 
1811         b = b + sintA*cosEpsB + costA*sinEpsB;
1812         b = b + sintB + costB*sinEpsA + sintB*cosEpsB + costB*sinEpsB;
1813 
1814         double sina = a + b;
1815         double sinb = -(sina - a - b);
1816 
1817         // Compute cosine
1818 
1819         a = b = c = d = 0.0;
1820 
1821         t = costA*cosEpsA;
1822         c = a + t;
1823         d = -(c - a - t);
1824         a = c;
1825         b = b + d;
1826 
1827         t = -sintA*sinEpsA;
1828         c = a + t;
1829         d = -(c - a - t);
1830         a = c;
1831         b = b + d;
1832 
1833         b = b + costB*cosEpsA + costA*cosEpsB + costB*cosEpsB;
1834         b = b - (sintB*sinEpsA + sintA*sinEpsB + sintB*sinEpsB);
1835 
1836         double cosa = a + b;
1837         double cosb = -(cosa - a - b);
1838 
1839         if (cotanFlag) {
1840             double tmp;
1841             tmp = cosa; cosa = sina; sina = tmp;
1842             tmp = cosb; cosb = sinb; sinb = tmp;
1843         }
1844 
1845 
1846         /* estimate and correct, compute 1.0/(cosa+cosb) */
1847         /*
1848     double est = (sina+sinb)/(cosa+cosb);
1849     double err = (sina - cosa*est) + (sinb - cosb*est);
1850     est += err/(cosa+cosb);
1851     err = (sina - cosa*est) + (sinb - cosb*est);
1852          */
1853 
1854         // f(x) = 1/x,   f'(x) = -1/x^2
1855 
1856         double est = sina/cosa;
1857 
1858         /* Split the estimate to get more accurate read on division rounding */
1859         temp = est * HEX_40000000;
1860         double esta = (est + temp) - temp;
1861         double estb =  est - esta;
1862 
1863         temp = cosa * HEX_40000000;
1864         double cosaa = (cosa + temp) - temp;
1865         double cosab =  cosa - cosaa;
1866 
1867         //double err = (sina - est*cosa)/cosa;  // Correction for division rounding
1868         double err = (sina - esta*cosaa - esta*cosab - estb*cosaa - estb*cosab)/cosa;  // Correction for division rounding
1869         err += sinb/cosa;                     // Change in est due to sinb
1870         err += -sina * cosb / cosa / cosa;    // Change in est due to cosb
1871 
1872         if (xb != 0.0) {
1873             // tan' = 1 + tan^2      cot' = -(1 + cot^2)
1874             // Approximate impact of xb
1875             double xbadj = xb + est*est*xb;
1876             if (cotanFlag) {
1877                 xbadj = -xbadj;
1878             }
1879 
1880             err += xbadj;
1881         }
1882 
1883         return est+err;
1884     }
1885 
1886     /** Reduce the input argument using the Payne and Hanek method.
1887      *  This is good for all inputs 0.0 < x < inf
1888      *  Output is remainder after dividing by PI/2
1889      *  The result array should contain 3 numbers.
1890      *  result[0] is the integer portion, so mod 4 this gives the quadrant.
1891      *  result[1] is the upper bits of the remainder
1892      *  result[2] is the lower bits of the remainder
1893      *
1894      * @param x number to reduce
1895      * @param result placeholder where to put the result
1896      */
1897     private static void reducePayneHanek(double x, double result[])
1898     {
1899         /* Convert input double to bits */
1900         long inbits = Double.doubleToLongBits(x);
1901         int exponent = (int) ((inbits >> 52) & 0x7ff) - 1023;
1902 
1903         /* Convert to fixed point representation */
1904         inbits &= 0x000fffffffffffffL;
1905         inbits |= 0x0010000000000000L;
1906 
1907         /* Normalize input to be between 0.5 and 1.0 */
1908         exponent++;
1909         inbits <<= 11;
1910 
1911         /* Based on the exponent, get a shifted copy of recip2pi */
1912         long shpi0;
1913         long shpiA;
1914         long shpiB;
1915         int idx = exponent >> 6;
1916         int shift = exponent - (idx << 6);
1917 
1918         if (shift != 0) {
1919             shpi0 = (idx == 0) ? 0 : (RECIP_2PI[idx-1] << shift);
1920             shpi0 |= RECIP_2PI[idx] >>> (64-shift);
1921             shpiA = (RECIP_2PI[idx] << shift) | (RECIP_2PI[idx+1] >>> (64-shift));
1922             shpiB = (RECIP_2PI[idx+1] << shift) | (RECIP_2PI[idx+2] >>> (64-shift));
1923         } else {
1924             shpi0 = (idx == 0) ? 0 : RECIP_2PI[idx-1];
1925             shpiA = RECIP_2PI[idx];
1926             shpiB = RECIP_2PI[idx+1];
1927         }
1928 
1929         /* Multiply input by shpiA */
1930         long a = inbits >>> 32;
1931         long b = inbits & 0xffffffffL;
1932 
1933         long c = shpiA >>> 32;
1934         long d = shpiA & 0xffffffffL;
1935 
1936         long ac = a * c;
1937         long bd = b * d;
1938         long bc = b * c;
1939         long ad = a * d;
1940 
1941         long prodB = bd + (ad << 32);
1942         long prodA = ac + (ad >>> 32);
1943 
1944         boolean bita = (bd & 0x8000000000000000L) != 0;
1945         boolean bitb = (ad & 0x80000000L ) != 0;
1946         boolean bitsum = (prodB & 0x8000000000000000L) != 0;
1947 
1948         /* Carry */
1949         if ( (bita && bitb) ||
1950                 ((bita || bitb) && !bitsum) ) {
1951             prodA++;
1952         }
1953 
1954         bita = (prodB & 0x8000000000000000L) != 0;
1955         bitb = (bc & 0x80000000L ) != 0;
1956 
1957         prodB = prodB + (bc << 32);
1958         prodA = prodA + (bc >>> 32);
1959 
1960         bitsum = (prodB & 0x8000000000000000L) != 0;
1961 
1962         /* Carry */
1963         if ( (bita && bitb) ||
1964                 ((bita || bitb) && !bitsum) ) {
1965             prodA++;
1966         }
1967 
1968         /* Multiply input by shpiB */
1969         c = shpiB >>> 32;
1970         d = shpiB & 0xffffffffL;
1971         ac = a * c;
1972         bc = b * c;
1973         ad = a * d;
1974 
1975         /* Collect terms */
1976         ac = ac + ((bc + ad) >>> 32);
1977 
1978         bita = (prodB & 0x8000000000000000L) != 0;
1979         bitb = (ac & 0x8000000000000000L ) != 0;
1980         prodB += ac;
1981         bitsum = (prodB & 0x8000000000000000L) != 0;
1982         /* Carry */
1983         if ( (bita && bitb) ||
1984                 ((bita || bitb) && !bitsum) ) {
1985             prodA++;
1986         }
1987 
1988         /* Multiply by shpi0 */
1989         c = shpi0 >>> 32;
1990         d = shpi0 & 0xffffffffL;
1991 
1992         bd = b * d;
1993         bc = b * c;
1994         ad = a * d;
1995 
1996         prodA += bd + ((bc + ad) << 32);
1997 
1998         /*
1999          * prodA, prodB now contain the remainder as a fraction of PI.  We want this as a fraction of
2000          * PI/2, so use the following steps:
2001          * 1.) multiply by 4.
2002          * 2.) do a fixed point muliply by PI/4.
2003          * 3.) Convert to floating point.
2004          * 4.) Multiply by 2
2005          */
2006 
2007         /* This identifies the quadrant */
2008         int intPart = (int)(prodA >>> 62);
2009 
2010         /* Multiply by 4 */
2011         prodA <<= 2;
2012         prodA |= prodB >>> 62;
2013         prodB <<= 2;
2014 
2015         /* Multiply by PI/4 */
2016         a = prodA >>> 32;
2017         b = prodA & 0xffffffffL;
2018 
2019         c = PI_O_4_BITS[0] >>> 32;
2020         d = PI_O_4_BITS[0] & 0xffffffffL;
2021 
2022         ac = a * c;
2023         bd = b * d;
2024         bc = b * c;
2025         ad = a * d;
2026 
2027         long prod2B = bd + (ad << 32);
2028         long prod2A = ac + (ad >>> 32);
2029 
2030         bita = (bd & 0x8000000000000000L) != 0;
2031         bitb = (ad & 0x80000000L ) != 0;
2032         bitsum = (prod2B & 0x8000000000000000L) != 0;
2033 
2034         /* Carry */
2035         if ( (bita && bitb) ||
2036                 ((bita || bitb) && !bitsum) ) {
2037             prod2A++;
2038         }
2039 
2040         bita = (prod2B & 0x8000000000000000L) != 0;
2041         bitb = (bc & 0x80000000L ) != 0;
2042 
2043         prod2B = prod2B + (bc << 32);
2044         prod2A = prod2A + (bc >>> 32);
2045 
2046         bitsum = (prod2B & 0x8000000000000000L) != 0;
2047 
2048         /* Carry */
2049         if ( (bita && bitb) ||
2050                 ((bita || bitb) && !bitsum) ) {
2051             prod2A++;
2052         }
2053 
2054         /* Multiply input by pio4bits[1] */
2055         c = PI_O_4_BITS[1] >>> 32;
2056         d = PI_O_4_BITS[1] & 0xffffffffL;
2057         ac = a * c;
2058         bc = b * c;
2059         ad = a * d;
2060 
2061         /* Collect terms */
2062         ac = ac + ((bc + ad) >>> 32);
2063 
2064         bita = (prod2B & 0x8000000000000000L) != 0;
2065         bitb = (ac & 0x8000000000000000L ) != 0;
2066         prod2B += ac;
2067         bitsum = (prod2B & 0x8000000000000000L) != 0;
2068         /* Carry */
2069         if ( (bita && bitb) ||
2070                 ((bita || bitb) && !bitsum) ) {
2071             prod2A++;
2072         }
2073 
2074         /* Multiply inputB by pio4bits[0] */
2075         a = prodB >>> 32;
2076         b = prodB & 0xffffffffL;
2077         c = PI_O_4_BITS[0] >>> 32;
2078         d = PI_O_4_BITS[0] & 0xffffffffL;
2079         ac = a * c;
2080         bc = b * c;
2081         ad = a * d;
2082 
2083         /* Collect terms */
2084         ac = ac + ((bc + ad) >>> 32);
2085 
2086         bita = (prod2B & 0x8000000000000000L) != 0;
2087         bitb = (ac & 0x8000000000000000L ) != 0;
2088         prod2B += ac;
2089         bitsum = (prod2B & 0x8000000000000000L) != 0;
2090         /* Carry */
2091         if ( (bita && bitb) ||
2092                 ((bita || bitb) && !bitsum) ) {
2093             prod2A++;
2094         }
2095 
2096         /* Convert to double */
2097         double tmpA = (prod2A >>> 12) / TWO_POWER_52;  // High order 52 bits
2098         double tmpB = (((prod2A & 0xfffL) << 40) + (prod2B >>> 24)) / TWO_POWER_52 / TWO_POWER_52; // Low bits
2099 
2100         double sumA = tmpA + tmpB;
2101         double sumB = -(sumA - tmpA - tmpB);
2102 
2103         /* Multiply by PI/2 and return */
2104         result[0] = intPart;
2105         result[1] = sumA * 2.0;
2106         result[2] = sumB * 2.0;
2107     }
2108 
2109     /**
2110      *  Sine function.
2111      *  @param x a number
2112      *  @return sin(x)
2113      */
2114     public static double sin(double x) {
2115         boolean negative = false;
2116         int quadrant = 0;
2117         double xa;
2118         double xb = 0.0;
2119 
2120         /* Take absolute value of the input */
2121         xa = x;
2122         if (x < 0) {
2123             negative = true;
2124             xa = -xa;
2125         }
2126 
2127         /* Check for zero and negative zero */
2128         if (xa == 0.0) {
2129             long bits = Double.doubleToLongBits(x);
2130             if (bits < 0) {
2131                 return -0.0;
2132             }
2133             return 0.0;
2134         }
2135 
2136         if (xa != xa || xa == Double.POSITIVE_INFINITY) {
2137             return Double.NaN;
2138         }
2139 
2140         /* Perform any argument reduction */
2141         if (xa > 3294198.0) {
2142             // PI * (2**20)
2143             // Argument too big for CodyWaite reduction.  Must use
2144             // PayneHanek.
2145             double reduceResults[] = new double[3];
2146             reducePayneHanek(xa, reduceResults);
2147             quadrant = ((int) reduceResults[0]) & 3;
2148             xa = reduceResults[1];
2149             xb = reduceResults[2];
2150         } else if (xa > 1.5707963267948966) {
2151             /* Inline the Cody/Waite reduction for performance */
2152 
2153             // Estimate k
2154             //k = (int)(xa / 1.5707963267948966);
2155             int k = (int)(xa * 0.6366197723675814);
2156 
2157             // Compute remainder
2158             double remA;
2159             double remB;
2160             while (true) {
2161                 double a = -k * 1.570796251296997;
2162                 remA = xa + a;
2163                 remB = -(remA - xa - a);
2164 
2165                 a = -k * 7.549789948768648E-8;
2166                 double b = remA;
2167                 remA = a + b;
2168                 remB += -(remA - b - a);
2169 
2170                 a = -k * 6.123233995736766E-17;
2171                 b = remA;
2172                 remA = a + b;
2173                 remB += -(remA - b - a);
2174 
2175                 if (remA > 0.0) {
2176                     break;
2177                 }
2178 
2179                 // Remainder is negative, so decrement k and try again.
2180                 // This should only happen if the input is very close
2181                 // to an even multiple of pi/2
2182                 k--;
2183             }
2184             quadrant = k & 3;
2185             xa = remA;
2186             xb = remB;
2187         }
2188 
2189         if (negative) {
2190             quadrant ^= 2;  // Flip bit 1
2191         }
2192 
2193         switch (quadrant) {
2194             case 0:
2195                 return sinQ(xa, xb);
2196             case 1:
2197                 return cosQ(xa, xb);
2198             case 2:
2199                 return -sinQ(xa, xb);
2200             case 3:
2201                 return -cosQ(xa, xb);
2202             default:
2203                 return Double.NaN;
2204         }
2205     }
2206 
2207     /**
2208      *  Cosine function
2209      *  @param x a number
2210      *  @return cos(x)
2211      */
2212     public static double cos(double x) {
2213         int quadrant = 0;
2214 
2215         /* Take absolute value of the input */
2216         double xa = x;
2217         if (x < 0) {
2218             xa = -xa;
2219         }
2220 
2221         if (xa != xa || xa == Double.POSITIVE_INFINITY) {
2222             return Double.NaN;
2223         }
2224 
2225         /* Perform any argument reduction */
2226         double xb = 0;
2227         if (xa > 3294198.0) {
2228             // PI * (2**20)
2229             // Argument too big for CodyWaite reduction.  Must use
2230             // PayneHanek.
2231             double reduceResults[] = new double[3];
2232             reducePayneHanek(xa, reduceResults);
2233             quadrant = ((int) reduceResults[0]) & 3;
2234             xa = reduceResults[1];
2235             xb = reduceResults[2];
2236         } else if (xa > 1.5707963267948966) {
2237             /* Inline the Cody/Waite reduction for performance */
2238 
2239             // Estimate k
2240             //k = (int)(xa / 1.5707963267948966);
2241             int k = (int)(xa * 0.6366197723675814);
2242 
2243             // Compute remainder
2244             double remA;
2245             double remB;
2246             while (true) {
2247                 double a = -k * 1.570796251296997;
2248                 remA = xa + a;
2249                 remB = -(remA - xa - a);
2250 
2251                 a = -k * 7.549789948768648E-8;
2252                 double b = remA;
2253                 remA = a + b;
2254                 remB += -(remA - b - a);
2255 
2256                 a = -k * 6.123233995736766E-17;
2257                 b = remA;
2258                 remA = a + b;
2259                 remB += -(remA - b - a);
2260 
2261                 if (remA > 0.0) {
2262                     break;
2263                 }
2264 
2265                 // Remainder is negative, so decrement k and try again.
2266                 // This should only happen if the input is very close
2267                 // to an even multiple of pi/2
2268                 k--;
2269             }
2270             quadrant = k & 3;
2271             xa = remA;
2272             xb = remB;
2273         }
2274 
2275         //if (negative)
2276         //  quadrant = (quadrant + 2) % 4;
2277 
2278         switch (quadrant) {
2279             case 0:
2280                 return cosQ(xa, xb);
2281             case 1:
2282                 return -sinQ(xa, xb);
2283             case 2:
2284                 return -cosQ(xa, xb);
2285             case 3:
2286                 return sinQ(xa, xb);
2287             default:
2288                 return Double.NaN;
2289         }
2290     }
2291 
2292     /**
2293      *   Tangent function
2294      *  @param x a number
2295      *  @return tan(x)
2296      */
2297     public static double tan(double x) {
2298         boolean negative = false;
2299         int quadrant = 0;
2300 
2301         /* Take absolute value of the input */
2302         double xa = x;
2303         if (x < 0) {
2304             negative = true;
2305             xa = -xa;
2306         }
2307 
2308         /* Check for zero and negative zero */
2309         if (xa == 0.0) {
2310             long bits = Double.doubleToLongBits(x);
2311             if (bits < 0) {
2312                 return -0.0;
2313             }
2314             return 0.0;
2315         }
2316 
2317         if (xa != xa || xa == Double.POSITIVE_INFINITY) {
2318             return Double.NaN;
2319         }
2320 
2321         /* Perform any argument reduction */
2322         double xb = 0;
2323         if (xa > 3294198.0) {
2324             // PI * (2**20)
2325             // Argument too big for CodyWaite reduction.  Must use
2326             // PayneHanek.
2327             double reduceResults[] = new double[3];
2328             reducePayneHanek(xa, reduceResults);
2329             quadrant = ((int) reduceResults[0]) & 3;
2330             xa = reduceResults[1];
2331             xb = reduceResults[2];
2332         } else if (xa > 1.5707963267948966) {
2333             /* Inline the Cody/Waite reduction for performance */
2334 
2335             // Estimate k
2336             //k = (int)(xa / 1.5707963267948966);
2337             int k = (int)(xa * 0.6366197723675814);
2338 
2339             // Compute remainder
2340             double remA;
2341             double remB;
2342             while (true) {
2343                 double a = -k * 1.570796251296997;
2344                 remA = xa + a;
2345                 remB = -(remA - xa - a);
2346 
2347                 a = -k * 7.549789948768648E-8;
2348                 double b = remA;
2349                 remA = a + b;
2350                 remB += -(remA - b - a);
2351 
2352                 a = -k * 6.123233995736766E-17;
2353                 b = remA;
2354                 remA = a + b;
2355                 remB += -(remA - b - a);
2356 
2357                 if (remA > 0.0) {
2358                     break;
2359                 }
2360 
2361                 // Remainder is negative, so decrement k and try again.
2362                 // This should only happen if the input is very close
2363                 // to an even multiple of pi/2
2364                 k--;
2365             }
2366             quadrant = k & 3;
2367             xa = remA;
2368             xb = remB;
2369         }
2370 
2371         if (xa > 1.5) {
2372             // Accurracy suffers between 1.5 and PI/2
2373             final double pi2a = 1.5707963267948966;
2374             final double pi2b = 6.123233995736766E-17;
2375 
2376             final double a = pi2a - xa;
2377             double b = -(a - pi2a + xa);
2378             b += pi2b - xb;
2379 
2380             xa = a + b;
2381             xb = -(xa - a - b);
2382             quadrant ^= 1;
2383             negative ^= true;
2384         }
2385 
2386         double result;
2387         if ((quadrant & 1) == 0) {
2388             result = tanQ(xa, xb, false);
2389         } else {
2390             result = -tanQ(xa, xb, true);
2391         }
2392 
2393         if (negative) {
2394             result = -result;
2395         }
2396 
2397         return result;
2398     }
2399 
2400     /**
2401      * Arctangent function
2402      *  @param x a number
2403      *  @return atan(x)
2404      */
2405     public static double atan(double x) {
2406         return atan(x, 0.0, false);
2407     }
2408 
2409     /** Internal helper function to compute arctangent.
2410      * @param xa number from which arctangent is requested
2411      * @param xb extra bits for x (may be 0.0)
2412      * @param leftPlane if true, result angle must be put in the left half plane
2413      * @return atan(xa + xb) (or angle shifted by {@code PI} if leftPlane is true)
2414      */
2415     private static double atan(double xa, double xb, boolean leftPlane) {
2416         boolean negate = false;
2417         int idx;
2418 
2419         if (xa == 0.0) { // Matches +/- 0.0; return correct sign
2420             return leftPlane ? copySign(Math.PI, xa) : xa;
2421         }
2422 
2423         if (xa < 0) {
2424             // negative
2425             xa = -xa;
2426             xb = -xb;
2427             negate = true;
2428         }
2429 
2430         if (xa > 1.633123935319537E16) { // Very large input
2431             return (negate ^ leftPlane) ? (-Math.PI/2.0) : (Math.PI/2.0);
2432         }
2433 
2434         /* Estimate the closest tabulated arctan value, compute eps = xa-tangentTable */
2435         if (xa < 1.0) {
2436             idx = (int) (((-1.7168146928204136 * xa * xa + 8.0) * xa) + 0.5);
2437         } else {
2438             double temp = 1.0/xa;
2439             idx = (int) (-((-1.7168146928204136 * temp * temp + 8.0) * temp) + 13.07);
2440         }
2441         double epsA = xa - TANGENT_TABLE_A[idx];
2442         double epsB = -(epsA - xa + TANGENT_TABLE_A[idx]);
2443         epsB += xb - TANGENT_TABLE_B[idx];
2444 
2445         double temp = epsA + epsB;
2446         epsB = -(temp - epsA - epsB);
2447         epsA = temp;
2448 
2449         /* Compute eps = eps / (1.0 + xa*tangent) */
2450         temp = xa * HEX_40000000;
2451         double ya = xa + temp - temp;
2452         double yb = xb + xa - ya;
2453         xa = ya;
2454         xb += yb;
2455 
2456         //if (idx > 8 || idx == 0)
2457         if (idx == 0) {
2458             /* If the slope of the arctan is gentle enough (< 0.45), this approximation will suffice */
2459             //double denom = 1.0 / (1.0 + xa*tangentTableA[idx] + xb*tangentTableA[idx] + xa*tangentTableB[idx] + xb*tangentTableB[idx]);
2460             double denom = 1.0 / (1.0 + (xa + xb) * (TANGENT_TABLE_A[idx] + TANGENT_TABLE_B[idx]));
2461             //double denom = 1.0 / (1.0 + xa*tangentTableA[idx]);
2462             ya = epsA * denom;
2463             yb = epsB * denom;
2464         } else {
2465             double temp2 = xa * TANGENT_TABLE_A[idx];
2466             double za = 1.0 + temp2;
2467             double zb = -(za - 1.0 - temp2);
2468             temp2 = xb * TANGENT_TABLE_A[idx] + xa * TANGENT_TABLE_B[idx];
2469             temp = za + temp2;
2470             zb += -(temp - za - temp2);
2471             za = temp;
2472 
2473             zb += xb * TANGENT_TABLE_B[idx];
2474             ya = epsA / za;
2475 
2476             temp = ya * HEX_40000000;
2477             final double yaa = (ya + temp) - temp;
2478             final double yab = ya - yaa;
2479 
2480             temp = za * HEX_40000000;
2481             final double zaa = (za + temp) - temp;
2482             final double zab = za - zaa;
2483 
2484             /* Correct for rounding in division */
2485             yb = (epsA - yaa * zaa - yaa * zab - yab * zaa - yab * zab) / za;
2486 
2487             yb += -epsA * zb / za / za;
2488             yb += epsB / za;
2489         }
2490 
2491 
2492         epsA = ya;
2493         epsB = yb;
2494 
2495         /* Evaluate polynomial */
2496         double epsA2 = epsA*epsA;
2497 
2498         /*
2499     yb = -0.09001346640161823;
2500     yb = yb * epsA2 + 0.11110718400605211;
2501     yb = yb * epsA2 + -0.1428571349122913;
2502     yb = yb * epsA2 + 0.19999999999273194;
2503     yb = yb * epsA2 + -0.33333333333333093;
2504     yb = yb * epsA2 * epsA;
2505          */
2506 
2507         yb = 0.07490822288864472;
2508         yb = yb * epsA2 + -0.09088450866185192;
2509         yb = yb * epsA2 + 0.11111095942313305;
2510         yb = yb * epsA2 + -0.1428571423679182;
2511         yb = yb * epsA2 + 0.19999999999923582;
2512         yb = yb * epsA2 + -0.33333333333333287;
2513         yb = yb * epsA2 * epsA;
2514 
2515 
2516         ya = epsA;
2517 
2518         temp = ya + yb;
2519         yb = -(temp - ya - yb);
2520         ya = temp;
2521 
2522         /* Add in effect of epsB.   atan'(x) = 1/(1+x^2) */
2523         yb += epsB / (1.0 + epsA * epsA);
2524 
2525         double result;
2526         double resultb;
2527 
2528         //result = yb + eighths[idx] + ya;
2529         double za = EIGHTHS[idx] + ya;
2530         double zb = -(za - EIGHTHS[idx] - ya);
2531         temp = za + yb;
2532         zb += -(temp - za - yb);
2533         za = temp;
2534 
2535         result = za + zb;
2536         resultb = -(result - za - zb);
2537 
2538         if (leftPlane) {
2539             // Result is in the left plane
2540             final double pia = 1.5707963267948966*2.0;
2541             final double pib = 6.123233995736766E-17*2.0;
2542 
2543             za = pia - result;
2544             zb = -(za - pia + result);
2545             zb += pib - resultb;
2546 
2547             result = za + zb;
2548             resultb = -(result - za - zb);
2549         }
2550 
2551 
2552         if (negate ^ leftPlane) {
2553             result = -result;
2554         }
2555 
2556         return result;
2557     }
2558 
2559     /**
2560      * Two arguments arctangent function
2561      * @param y ordinate
2562      * @param x abscissa
2563      * @return phase angle of point (x,y) between {@code -PI} and {@code PI}
2564      */
2565     public static double atan2(double y, double x) {
2566         if (x !=x || y != y) {
2567             return Double.NaN;
2568         }
2569 
2570         if (y == 0.0) {
2571             double result = x*y;
2572             double invx = 1.0/x;
2573             double invy = 1.0/y;
2574 
2575             if (invx == 0.0) { // X is infinite
2576                 if (x > 0) {
2577                     return y; // return +/- 0.0
2578                 } else {
2579                     return copySign(Math.PI, y);
2580                 }
2581             }
2582 
2583             if (x < 0.0 || invx < 0.0) {
2584                 if (y < 0.0 || invy < 0.0) {
2585                     return -Math.PI;
2586                 } else {
2587                     return Math.PI;
2588                 }
2589             } else {
2590                 return result;
2591             }
2592         }
2593 
2594         // y cannot now be zero
2595 
2596         if (y == Double.POSITIVE_INFINITY) {
2597             if (x == Double.POSITIVE_INFINITY) {
2598                 return Math.PI/4.0;
2599             }
2600 
2601             if (x == Double.NEGATIVE_INFINITY) {
2602                 return Math.PI * F_3_4;
2603             }
2604 
2605             return Math.PI/2.0;
2606         }
2607 
2608         if (y == Double.NEGATIVE_INFINITY) {
2609             if (x == Double.POSITIVE_INFINITY) {
2610                 return -Math.PI/4.0;
2611             }
2612 
2613             if (x == Double.NEGATIVE_INFINITY) {
2614                 return -Math.PI * F_3_4;
2615             }
2616 
2617             return -Math.PI/2.0;
2618         }
2619 
2620         if (x == Double.POSITIVE_INFINITY) {
2621             if (y > 0.0 || 1/y > 0.0) {
2622                 return 0.0;
2623             }
2624 
2625             if (y < 0.0 || 1/y < 0.0) {
2626                 return -0.0;
2627             }
2628         }
2629 
2630         if (x == Double.NEGATIVE_INFINITY)
2631         {
2632             if (y > 0.0 || 1/y > 0.0) {
2633                 return Math.PI;
2634             }
2635 
2636             if (y < 0.0 || 1/y < 0.0) {
2637                 return -Math.PI;
2638             }
2639         }
2640 
2641         // Neither y nor x can be infinite or NAN here
2642 
2643         if (x == 0) {
2644             if (y > 0.0 || 1/y > 0.0) {
2645                 return Math.PI/2.0;
2646             }
2647 
2648             if (y < 0.0 || 1/y < 0.0) {
2649                 return -Math.PI/2.0;
2650             }
2651         }
2652 
2653         // Compute ratio r = y/x
2654         final double r = y/x;
2655         if (Double.isInfinite(r)) { // bypass calculations that can create NaN
2656             return atan(r, 0, x < 0);
2657         }
2658 
2659         double ra = doubleHighPart(r);
2660         double rb = r - ra;
2661 
2662         // Split x
2663         final double xa = doubleHighPart(x);
2664         final double xb = x - xa;
2665 
2666         rb += (y - ra * xa - ra * xb - rb * xa - rb * xb) / x;
2667 
2668         double temp = ra + rb;
2669         rb = -(temp - ra - rb);
2670         ra = temp;
2671 
2672         if (ra == 0) { // Fix up the sign so atan works correctly
2673             ra = copySign(0.0, y);
2674         }
2675 
2676         // Call atan
2677         double result = atan(ra, rb, x < 0);
2678 
2679         return result;
2680     }
2681 
2682     /** Compute the arc sine of a number.
2683      * @param x number on which evaluation is done
2684      * @return arc sine of x
2685      */
2686     public static double asin(double x) {
2687       if (x != x) {
2688           return Double.NaN;
2689       }
2690 
2691       if (x > 1.0 || x < -1.0) {
2692           return Double.NaN;
2693       }
2694 
2695       if (x == 1.0) {
2696           return Math.PI/2.0;
2697       }
2698 
2699       if (x == -1.0) {
2700           return -Math.PI/2.0;
2701       }
2702 
2703       if (x == 0.0) { // Matches +/- 0.0; return correct sign
2704           return x;
2705       }
2706 
2707       /* Compute asin(x) = atan(x/sqrt(1-x*x)) */
2708 
2709       /* Split x */
2710       double temp = x * HEX_40000000;
2711       final double xa = x + temp - temp;
2712       final double xb = x - xa;
2713 
2714       /* Square it */
2715       double ya = xa*xa;
2716       double yb = xa*xb*2.0 + xb*xb;
2717 
2718       /* Subtract from 1 */
2719       ya = -ya;
2720       yb = -yb;
2721 
2722       double za = 1.0 + ya;
2723       double zb = -(za - 1.0 - ya);
2724 
2725       temp = za + yb;
2726       zb += -(temp - za - yb);
2727       za = temp;
2728 
2729       /* Square root */
2730       double y;
2731       y = sqrt(za);
2732       temp = y * HEX_40000000;
2733       ya = y + temp - temp;
2734       yb = y - ya;
2735 
2736       /* Extend precision of sqrt */
2737       yb += (za - ya*ya - 2*ya*yb - yb*yb) / (2.0*y);
2738 
2739       /* Contribution of zb to sqrt */
2740       double dx = zb / (2.0*y);
2741 
2742       // Compute ratio r = x/y
2743       double r = x/y;
2744       temp = r * HEX_40000000;
2745       double ra = r + temp - temp;
2746       double rb = r - ra;
2747 
2748       rb += (x - ra*ya - ra*yb - rb*ya - rb*yb) / y;  // Correct for rounding in division
2749       rb += -x * dx / y / y;  // Add in effect additional bits of sqrt.
2750 
2751       temp = ra + rb;
2752       rb = -(temp - ra - rb);
2753       ra = temp;
2754 
2755       return atan(ra, rb, false);
2756     }
2757 
2758     /** Compute the arc cosine of a number.
2759      * @param x number on which evaluation is done
2760      * @return arc cosine of x
2761      */
2762     public static double acos(double x) {
2763       if (x != x) {
2764           return Double.NaN;
2765       }
2766 
2767       if (x > 1.0 || x < -1.0) {
2768           return Double.NaN;
2769       }
2770 
2771       if (x == -1.0) {
2772           return Math.PI;
2773       }
2774 
2775       if (x == 1.0) {
2776           return 0.0;
2777       }
2778 
2779       if (x == 0) {
2780           return Math.PI/2.0;
2781       }
2782 
2783       /* Compute acos(x) = atan(sqrt(1-x*x)/x) */
2784 
2785       /* Split x */
2786       double temp = x * HEX_40000000;
2787       final double xa = x + temp - temp;
2788       final double xb = x - xa;
2789 
2790       /* Square it */
2791       double ya = xa*xa;
2792       double yb = xa*xb*2.0 + xb*xb;
2793 
2794       /* Subtract from 1 */
2795       ya = -ya;
2796       yb = -yb;
2797 
2798       double za = 1.0 + ya;
2799       double zb = -(za - 1.0 - ya);
2800 
2801       temp = za + yb;
2802       zb += -(temp - za - yb);
2803       za = temp;
2804 
2805       /* Square root */
2806       double y = sqrt(za);
2807       temp = y * HEX_40000000;
2808       ya = y + temp - temp;
2809       yb = y - ya;
2810 
2811       /* Extend precision of sqrt */
2812       yb += (za - ya*ya - 2*ya*yb - yb*yb) / (2.0*y);
2813 
2814       /* Contribution of zb to sqrt */
2815       yb += zb / (2.0*y);
2816       y = ya+yb;
2817       yb = -(y - ya - yb);
2818 
2819       // Compute ratio r = y/x
2820       double r = y/x;
2821 
2822       // Did r overflow?
2823       if (Double.isInfinite(r)) { // x is effectively zero
2824           return Math.PI/2; // so return the appropriate value
2825       }
2826 
2827       double ra = doubleHighPart(r);
2828       double rb = r - ra;
2829 
2830       rb += (y - ra*xa - ra*xb - rb*xa - rb*xb) / x;  // Correct for rounding in division
2831       rb += yb / x;  // Add in effect additional bits of sqrt.
2832 
2833       temp = ra + rb;
2834       rb = -(temp - ra - rb);
2835       ra = temp;
2836 
2837       return atan(ra, rb, x<0);
2838     }
2839 
2840     /** Compute the cubic root of a number.
2841      * @param x number on which evaluation is done
2842      * @return cubic root of x
2843      */
2844     public static double cbrt(double x) {
2845       /* Convert input double to bits */
2846       long inbits = Double.doubleToLongBits(x);
2847       int exponent = (int) ((inbits >> 52) & 0x7ff) - 1023;
2848       boolean subnormal = false;
2849 
2850       if (exponent == -1023) {
2851           if (x == 0) {
2852               return x;
2853           }
2854 
2855           /* Subnormal, so normalize */
2856           subnormal = true;
2857           x *= 1.8014398509481984E16;  // 2^54
2858           inbits = Double.doubleToLongBits(x);
2859           exponent = (int) ((inbits >> 52) & 0x7ff) - 1023;
2860       }
2861 
2862       if (exponent == 1024) {
2863           // Nan or infinity.  Don't care which.
2864           return x;
2865       }
2866 
2867       /* Divide the exponent by 3 */
2868       int exp3 = exponent / 3;
2869 
2870       /* p2 will be the nearest power of 2 to x with its exponent divided by 3 */
2871       double p2 = Double.longBitsToDouble((inbits & 0x8000000000000000L) |
2872                                           (long)(((exp3 + 1023) & 0x7ff)) << 52);
2873 
2874       /* This will be a number between 1 and 2 */
2875       final double mant = Double.longBitsToDouble((inbits & 0x000fffffffffffffL) | 0x3ff0000000000000L);
2876 
2877       /* Estimate the cube root of mant by polynomial */
2878       double est = -0.010714690733195933;
2879       est = est * mant + 0.0875862700108075;
2880       est = est * mant + -0.3058015757857271;
2881       est = est * mant + 0.7249995199969751;
2882       est = est * mant + 0.5039018405998233;
2883 
2884       est *= CBRTTWO[exponent % 3 + 2];
2885 
2886       // est should now be good to about 15 bits of precision.   Do 2 rounds of
2887       // Newton's method to get closer,  this should get us full double precision
2888       // Scale down x for the purpose of doing newtons method.  This avoids over/under flows.
2889       final double xs = x / (p2*p2*p2);
2890       est += (xs - est*est*est) / (3*est*est);
2891       est += (xs - est*est*est) / (3*est*est);
2892 
2893       // Do one round of Newton's method in extended precision to get the last bit right.
2894       double temp = est * HEX_40000000;
2895       double ya = est + temp - temp;
2896       double yb = est - ya;
2897 
2898       double za = ya * ya;
2899       double zb = ya * yb * 2.0 + yb * yb;
2900       temp = za * HEX_40000000;
2901       double temp2 = za + temp - temp;
2902       zb += za - temp2;
2903       za = temp2;
2904 
2905       zb = za * yb + ya * zb + zb * yb;
2906       za = za * ya;
2907 
2908       double na = xs - za;
2909       double nb = -(na - xs + za);
2910       nb -= zb;
2911 
2912       est += (na+nb)/(3*est*est);
2913 
2914       /* Scale by a power of two, so this is exact. */
2915       est *= p2;
2916 
2917       if (subnormal) {
2918           est *= 3.814697265625E-6;  // 2^-18
2919       }
2920 
2921       return est;
2922     }
2923 
2924     /**
2925      *  Convert degrees to radians, with error of less than 0.5 ULP
2926      *  @param x angle in degrees
2927      *  @return x converted into radians
2928      */
2929     public static double toRadians(double x)
2930     {
2931         if (Double.isInfinite(x) || x == 0.0) { // Matches +/- 0.0; return correct sign
2932             return x;
2933         }
2934 
2935         // These are PI/180 split into high and low order bits
2936         final double facta = 0.01745329052209854;
2937         final double factb = 1.997844754509471E-9;
2938 
2939         double xa = doubleHighPart(x);
2940         double xb = x - xa;
2941 
2942         double result = xb * factb + xb * facta + xa * factb + xa * facta;
2943         if (result == 0) {
2944             result = result * x; // ensure correct sign if calculation underflows
2945         }
2946         return result;
2947     }
2948 
2949     /**
2950      *  Convert radians to degrees, with error of less than 0.5 ULP
2951      *  @param x angle in radians
2952      *  @return x converted into degrees
2953      */
2954     public static double toDegrees(double x)
2955     {
2956         if (Double.isInfinite(x) || x == 0.0) { // Matches +/- 0.0; return correct sign
2957             return x;
2958         }
2959 
2960         // These are 180/PI split into high and low order bits
2961         final double facta = 57.2957763671875;
2962         final double factb = 3.145894820876798E-6;
2963 
2964         double xa = doubleHighPart(x);
2965         double xb = x - xa;
2966 
2967         return xb * factb + xb * facta + xa * factb + xa * facta;
2968     }
2969 
2970     /**
2971      * Absolute value.
2972      * @param x number from which absolute value is requested
2973      * @return abs(x)
2974      */
2975     public static int abs(final int x) {
2976         return (x < 0) ? -x : x;
2977     }
2978 
2979     /**
2980      * Absolute value.
2981      * @param x number from which absolute value is requested
2982      * @return abs(x)
2983      */
2984     public static long abs(final long x) {
2985         return (x < 0l) ? -x : x;
2986     }
2987 
2988     /**
2989      * Absolute value.
2990      * @param x number from which absolute value is requested
2991      * @return abs(x)
2992      */
2993     public static float abs(final float x) {
2994         return (x < 0.0f) ? -x : (x == 0.0f) ? 0.0f : x; // -0.0 => +0.0
2995     }
2996 
2997     /**
2998      * Absolute value.
2999      * @param x number from which absolute value is requested
3000      * @return abs(x)
3001      */
3002     public static double abs(double x) {
3003         return (x < 0.0) ? -x : (x == 0.0) ? 0.0 : x; // -0.0 => +0.0
3004     }
3005 
3006     /**
3007      * Compute least significant bit (Unit in Last Position) for a number.
3008      * @param x number from which ulp is requested
3009      * @return ulp(x)
3010      */
3011     public static double ulp(double x) {
3012         if (Double.isInfinite(x)) {
3013             return Double.POSITIVE_INFINITY;
3014         }
3015         return abs(x - Double.longBitsToDouble(Double.doubleToLongBits(x) ^ 1));
3016     }
3017 
3018     /**
3019      * Compute least significant bit (Unit in Last Position) for a number.
3020      * @param x number from which ulp is requested
3021      * @return ulp(x)
3022      */
3023     public static float ulp(float x) {
3024         if (Float.isInfinite(x)) {
3025             return Float.POSITIVE_INFINITY;
3026         }
3027         return abs(x - Float.intBitsToFloat(Float.floatToIntBits(x) ^ 1));
3028     }
3029 
3030     /**
3031      * Multiply a double number by a power of 2.
3032      * @param d number to multiply
3033      * @param n power of 2
3034      * @return d &times; 2<sup>n</sup>
3035      */
3036     public static double scalb(final double d, final int n) {
3037 
3038         // first simple and fast handling when 2^n can be represented using normal numbers
3039         if ((n > -1023) && (n < 1024)) {
3040             return d * Double.longBitsToDouble(((long) (n + 1023)) << 52);
3041         }
3042 
3043         // handle special cases
3044         if (Double.isNaN(d) || Double.isInfinite(d) || (d == 0)) {
3045             return d;
3046         }
3047         if (n < -2098) {
3048             return (d > 0) ? 0.0 : -0.0;
3049         }
3050         if (n > 2097) {
3051             return (d > 0) ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY;
3052         }
3053 
3054         // decompose d
3055         final long bits = Double.doubleToLongBits(d);
3056         final long sign = bits & 0x8000000000000000L;
3057         int  exponent   = ((int) (bits >>> 52)) & 0x7ff;
3058         long mantissa   = bits & 0x000fffffffffffffL;
3059 
3060         // compute scaled exponent
3061         int scaledExponent = exponent + n;
3062 
3063         if (n < 0) {
3064             // we are really in the case n <= -1023
3065             if (scaledExponent > 0) {
3066                 // both the input and the result are normal numbers, we only adjust the exponent
3067                 return Double.longBitsToDouble(sign | (((long) scaledExponent) << 52) | mantissa);
3068             } else if (scaledExponent > -53) {
3069                 // the input is a normal number and the result is a subnormal number
3070 
3071                 // recover the hidden mantissa bit
3072                 mantissa = mantissa | (1L << 52);
3073 
3074                 // scales down complete mantissa, hence losing least significant bits
3075                 final long mostSignificantLostBit = mantissa & (1L << (-scaledExponent));
3076                 mantissa = mantissa >>> (1 - scaledExponent);
3077                 if (mostSignificantLostBit != 0) {
3078                     // we need to add 1 bit to round up the result
3079                     mantissa++;
3080                 }
3081                 return Double.longBitsToDouble(sign | mantissa);
3082 
3083             } else {
3084                 // no need to compute the mantissa, the number scales down to 0
3085                 return (sign == 0L) ? 0.0 : -0.0;
3086             }
3087         } else {
3088             // we are really in the case n >= 1024
3089             if (exponent == 0) {
3090 
3091                 // the input number is subnormal, normalize it
3092                 while ((mantissa >>> 52) != 1) {
3093                     mantissa = mantissa << 1;
3094                     --scaledExponent;
3095                 }
3096                 ++scaledExponent;
3097                 mantissa = mantissa & 0x000fffffffffffffL;
3098 
3099                 if (scaledExponent < 2047) {
3100                     return Double.longBitsToDouble(sign | (((long) scaledExponent) << 52) | mantissa);
3101                 } else {
3102                     return (sign == 0L) ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY;
3103                 }
3104 
3105             } else if (scaledExponent < 2047) {
3106                 return Double.longBitsToDouble(sign | (((long) scaledExponent) << 52) | mantissa);
3107             } else {
3108                 return (sign == 0L) ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY;
3109             }
3110         }
3111 
3112     }
3113 
3114     /**
3115      * Multiply a float number by a power of 2.
3116      * @param f number to multiply
3117      * @param n power of 2
3118      * @return f &times; 2<sup>n</sup>
3119      */
3120     public static float scalb(final float f, final int n) {
3121 
3122         // first simple and fast handling when 2^n can be represented using normal numbers
3123         if ((n > -127) && (n < 128)) {
3124             return f * Float.intBitsToFloat((n + 127) << 23);
3125         }
3126 
3127         // handle special cases
3128         if (Float.isNaN(f) || Float.isInfinite(f) || (f == 0f)) {
3129             return f;
3130         }
3131         if (n < -277) {
3132             return (f > 0) ? 0.0f : -0.0f;
3133         }
3134         if (n > 276) {
3135             return (f > 0) ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY;
3136         }
3137 
3138         // decompose f
3139         final int bits = Float.floatToIntBits(f);
3140         final int sign = bits & 0x80000000;
3141         int  exponent  = (bits >>> 23) & 0xff;
3142         int mantissa   = bits & 0x007fffff;
3143 
3144         // compute scaled exponent
3145         int scaledExponent = exponent + n;
3146 
3147         if (n < 0) {
3148             // we are really in the case n <= -127
3149             if (scaledExponent > 0) {
3150                 // both the input and the result are normal numbers, we only adjust the exponent
3151                 return Float.intBitsToFloat(sign | (scaledExponent << 23) | mantissa);
3152             } else if (scaledExponent > -24) {
3153                 // the input is a normal number and the result is a subnormal number
3154 
3155                 // recover the hidden mantissa bit
3156                 mantissa = mantissa | (1 << 23);
3157 
3158                 // scales down complete mantissa, hence losing least significant bits
3159                 final int mostSignificantLostBit = mantissa & (1 << (-scaledExponent));
3160                 mantissa = mantissa >>> (1 - scaledExponent);
3161                 if (mostSignificantLostBit != 0) {
3162                     // we need to add 1 bit to round up the result
3163                     mantissa++;
3164                 }
3165                 return Float.intBitsToFloat(sign | mantissa);
3166 
3167             } else {
3168                 // no need to compute the mantissa, the number scales down to 0
3169                 return (sign == 0) ? 0.0f : -0.0f;
3170             }
3171         } else {
3172             // we are really in the case n >= 128
3173             if (exponent == 0) {
3174 
3175                 // the input number is subnormal, normalize it
3176                 while ((mantissa >>> 23) != 1) {
3177                     mantissa = mantissa << 1;
3178                     --scaledExponent;
3179                 }
3180                 ++scaledExponent;
3181                 mantissa = mantissa & 0x007fffff;
3182 
3183                 if (scaledExponent < 255) {
3184                     return Float.intBitsToFloat(sign | (scaledExponent << 23) | mantissa);
3185                 } else {
3186                     return (sign == 0) ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY;
3187                 }
3188 
3189             } else if (scaledExponent < 255) {
3190                 return Float.intBitsToFloat(sign | (scaledExponent << 23) | mantissa);
3191             } else {
3192                 return (sign == 0) ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY;
3193             }
3194         }
3195 
3196     }
3197 
3198     /**
3199      * Get the next machine representable number after a number, moving
3200      * in the direction of another number.
3201      * <p>
3202      * The ordering is as follows (increasing):
3203      * <ul>
3204      * <li>-INFINITY</li>
3205      * <li>-MAX_VALUE</li>
3206      * <li>-MIN_VALUE</li>
3207      * <li>-0.0</li>
3208      * <li>+0.0</li>
3209      * <li>+MIN_VALUE</li>
3210      * <li>+MAX_VALUE</li>
3211      * <li>+INFINITY</li>
3212      * <li></li>
3213      * <p>
3214      * If arguments compare equal, then the second argument is returned.
3215      * <p>
3216      * If {@code direction} is greater than {@code d},
3217      * the smallest machine representable number strictly greater than
3218      * {@code d} is returned; if less, then the largest representable number
3219      * strictly less than {@code d} is returned.</p>
3220      * <p>
3221      * If {@code d} is infinite and direction does not
3222      * bring it back to finite numbers, it is returned unchanged.</p>
3223      *
3224      * @param d base number
3225      * @param direction (the only important thing is whether
3226      * {@code direction} is greater or smaller than {@code d})
3227      * @return the next machine representable number in the specified direction
3228      */
3229     public static double nextAfter(double d, double direction) {
3230 
3231         // handling of some important special cases
3232         if (Double.isNaN(d) || Double.isNaN(direction)) {
3233             return Double.NaN;
3234         } else if (d == direction) {
3235             return direction;
3236         } else if (Double.isInfinite(d)) {
3237             return (d < 0) ? -Double.MAX_VALUE : Double.MAX_VALUE;
3238         } else if (d == 0) {
3239             return (direction < 0) ? -Double.MIN_VALUE : Double.MIN_VALUE;
3240         }
3241         // special cases MAX_VALUE to infinity and  MIN_VALUE to 0
3242         // are handled just as normal numbers
3243 
3244         final long bits = Double.doubleToLongBits(d);
3245         final long sign = bits & 0x8000000000000000L;
3246         if ((direction < d) ^ (sign == 0L)) {
3247             return Double.longBitsToDouble(sign | ((bits & 0x7fffffffffffffffL) + 1));
3248         } else {
3249             return Double.longBitsToDouble(sign | ((bits & 0x7fffffffffffffffL) - 1));
3250         }
3251 
3252     }
3253 
3254     /**
3255      * Get the next machine representable number after a number, moving
3256      * in the direction of another number.
3257      * <p>
3258      * The ordering is as follows (increasing):
3259      * <ul>
3260      * <li>-INFINITY</li>
3261      * <li>-MAX_VALUE</li>
3262      * <li>-MIN_VALUE</li>
3263      * <li>-0.0</li>
3264      * <li>+0.0</li>
3265      * <li>+MIN_VALUE</li>
3266      * <li>+MAX_VALUE</li>
3267      * <li>+INFINITY</li>
3268      * <li></li>
3269      * <p>
3270      * If arguments compare equal, then the second argument is returned.
3271      * <p>
3272      * If {@code direction} is greater than {@code f},
3273      * the smallest machine representable number strictly greater than
3274      * {@code f} is returned; if less, then the largest representable number
3275      * strictly less than {@code f} is returned.</p>
3276      * <p>
3277      * If {@code f} is infinite and direction does not
3278      * bring it back to finite numbers, it is returned unchanged.</p>
3279      *
3280      * @param f base number
3281      * @param direction (the only important thing is whether
3282      * {@code direction} is greater or smaller than {@code f})
3283      * @return the next machine representable number in the specified direction
3284      */
3285     public static float nextAfter(final float f, final double direction) {
3286 
3287         // handling of some important special cases
3288         if (Double.isNaN(f) || Double.isNaN(direction)) {
3289             return Float.NaN;
3290         } else if (f == direction) {
3291             return (float) direction;
3292         } else if (Float.isInfinite(f)) {
3293             return (f < 0f) ? -Float.MAX_VALUE : Float.MAX_VALUE;
3294         } else if (f == 0f) {
3295             return (direction < 0) ? -Float.MIN_VALUE : Float.MIN_VALUE;
3296         }
3297         // special cases MAX_VALUE to infinity and  MIN_VALUE to 0
3298         // are handled just as normal numbers
3299 
3300         final int bits = Float.floatToIntBits(f);
3301         final int sign = bits & 0x80000000;
3302         if ((direction < f) ^ (sign == 0)) {
3303             return Float.intBitsToFloat(sign | ((bits & 0x7fffffff) + 1));
3304         } else {
3305             return Float.intBitsToFloat(sign | ((bits & 0x7fffffff) - 1));
3306         }
3307 
3308     }
3309 
3310     /** Get the largest whole number smaller than x.
3311      * @param x number from which floor is requested
3312      * @return a double number f such that f is an integer f <= x < f + 1.0
3313      */
3314     public static double floor(double x) {
3315         long y;
3316 
3317         if (x != x) { // NaN
3318             return x;
3319         }
3320 
3321         if (x >= TWO_POWER_52 || x <= -TWO_POWER_52) {
3322             return x;
3323         }
3324 
3325         y = (long) x;
3326         if (x < 0 && y != x) {
3327             y--;
3328         }
3329 
3330         if (y == 0) {
3331             return x*y;
3332         }
3333 
3334         return y;
3335     }
3336 
3337     /** Get the smallest whole number larger than x.
3338      * @param x number from which ceil is requested
3339      * @return a double number c such that c is an integer c - 1.0 < x <= c
3340      */
3341     public static double ceil(double x) {
3342         double y;
3343 
3344         if (x != x) { // NaN
3345             return x;
3346         }
3347 
3348         y = floor(x);
3349         if (y == x) {
3350             return y;
3351         }
3352 
3353         y += 1.0;
3354 
3355         if (y == 0) {
3356             return x*y;
3357         }
3358 
3359         return y;
3360     }
3361 
3362     /** Get the whole number that is the nearest to x, or the even one if x is exactly half way between two integers.
3363      * @param x number from which nearest whole number is requested
3364      * @return a double number r such that r is an integer r - 0.5 <= x <= r + 0.5
3365      */
3366     public static double rint(double x) {
3367         double y = floor(x);
3368         double d = x - y;
3369 
3370         if (d > 0.5) {
3371             if (y == -1.0) {
3372                 return -0.0; // Preserve sign of operand
3373             }
3374             return y+1.0;
3375         }
3376         if (d < 0.5) {
3377             return y;
3378         }
3379 
3380         /* half way, round to even */
3381         long z = (long) y;
3382         return (z & 1) == 0 ? y : y + 1.0;
3383     }
3384 
3385     /** Get the closest long to x.
3386      * @param x number from which closest long is requested
3387      * @return closest long to x
3388      */
3389     public static long round(double x) {
3390         return (long) floor(x + 0.5);
3391     }
3392 
3393     /** Get the closest int to x.
3394      * @param x number from which closest int is requested
3395      * @return closest int to x
3396      */
3397     public static int round(final float x) {
3398         return (int) floor(x + 0.5f);
3399     }
3400 
3401     /** Compute the minimum of two values
3402      * @param a first value
3403      * @param b second value
3404      * @return a if a is lesser or equal to b, b otherwise
3405      */
3406     public static int min(final int a, final int b) {
3407         return (a <= b) ? a : b;
3408     }
3409 
3410     /** Compute the minimum of two values
3411      * @param a first value
3412      * @param b second value
3413      * @return a if a is lesser or equal to b, b otherwise
3414      */
3415     public static long min(final long a, final long b) {
3416         return (a <= b) ? a : b;
3417     }
3418 
3419     /** Compute the minimum of two values
3420      * @param a first value
3421      * @param b second value
3422      * @return a if a is lesser or equal to b, b otherwise
3423      */
3424     public static float min(final float a, final float b) {
3425         if (a > b) {
3426             return b;
3427         }
3428         if (a < b) {
3429             return a;
3430         }
3431         /* if either arg is NaN, return NaN */
3432         if (a != b) {
3433             return Float.NaN;
3434         }
3435         /* min(+0.0,-0.0) == -0.0 */
3436         /* 0x80000000 == Float.floatToRawIntBits(-0.0d) */
3437         int bits = Float.floatToRawIntBits(a);
3438         if (bits == 0x80000000) {
3439             return a;
3440         }
3441         return b;
3442     }
3443 
3444     /** Compute the minimum of two values
3445      * @param a first value
3446      * @param b second value
3447      * @return a if a is lesser or equal to b, b otherwise
3448      */
3449     public static double min(final double a, final double b) {
3450         if (a > b) {
3451             return b;
3452         }
3453         if (a < b) {
3454             return a;
3455         }
3456         /* if either arg is NaN, return NaN */
3457         if (a != b) {
3458             return Double.NaN;
3459         }
3460         /* min(+0.0,-0.0) == -0.0 */
3461         /* 0x8000000000000000L == Double.doubleToRawLongBits(-0.0d) */
3462         long bits = Double.doubleToRawLongBits(a);
3463         if (bits == 0x8000000000000000L) {
3464             return a;
3465         }
3466         return b;
3467     }
3468 
3469     /** Compute the maximum of two values
3470      * @param a first value
3471      * @param b second value
3472      * @return b if a is lesser or equal to b, a otherwise
3473      */
3474     public static int max(final int a, final int b) {
3475         return (a <= b) ? b : a;
3476     }
3477 
3478     /** Compute the maximum of two values
3479      * @param a first value
3480      * @param b second value
3481      * @return b if a is lesser or equal to b, a otherwise
3482      */
3483     public static long max(final long a, final long b) {
3484         return (a <= b) ? b : a;
3485     }
3486 
3487     /** Compute the maximum of two values
3488      * @param a first value
3489      * @param b second value
3490      * @return b if a is lesser or equal to b, a otherwise
3491      */
3492     public static float max(final float a, final float b) {
3493         if (a > b) {
3494             return a;
3495         }
3496         if (a < b) {
3497             return b;
3498         }
3499         /* if either arg is NaN, return NaN */
3500         if (a != b) {
3501             return Float.NaN;
3502         }
3503         /* min(+0.0,-0.0) == -0.0 */
3504         /* 0x80000000 == Float.floatToRawIntBits(-0.0d) */
3505         int bits = Float.floatToRawIntBits(a);
3506         if (bits == 0x80000000) {
3507             return b;
3508         }
3509         return a;
3510     }
3511 
3512     /** Compute the maximum of two values
3513      * @param a first value
3514      * @param b second value
3515      * @return b if a is lesser or equal to b, a otherwise
3516      */
3517     public static double max(final double a, final double b) {
3518         if (a > b) {
3519             return a;
3520         }
3521         if (a < b) {
3522             return b;
3523         }
3524         /* if either arg is NaN, return NaN */
3525         if (a != b) {
3526             return Double.NaN;
3527         }
3528         /* min(+0.0,-0.0) == -0.0 */
3529         /* 0x8000000000000000L == Double.doubleToRawLongBits(-0.0d) */
3530         long bits = Double.doubleToRawLongBits(a);
3531         if (bits == 0x8000000000000000L) {
3532             return b;
3533         }
3534         return a;
3535     }
3536 
3537     /**
3538      * Returns the hypotenuse of a triangle with sides {@code x} and {@code y}
3539      * - sqrt(<i>x</i><sup>2</sup>&nbsp;+<i>y</i><sup>2</sup>)<br/>
3540      * avoiding intermediate overflow or underflow.
3541      *
3542      * <ul>
3543      * <li> If either argument is infinite, then the result is positive infinity.</li>
3544      * <li> else, if either argument is NaN then the result is NaN.</li>
3545      * </ul>
3546      *
3547      * @param x a value
3548      * @param y a value
3549      * @return sqrt(<i>x</i><sup>2</sup>&nbsp;+<i>y</i><sup>2</sup>)
3550      */
3551     public static double hypot(final double x, final double y) {
3552         if (Double.isInfinite(x) || Double.isInfinite(y)) {
3553             return Double.POSITIVE_INFINITY;
3554         } else if (Double.isNaN(x) || Double.isNaN(y)) {
3555             return Double.NaN;
3556         } else {
3557 
3558             final int expX = getExponent(x);
3559             final int expY = getExponent(y);
3560             if (expX > expY + 27) {
3561                 // y is neglectible with respect to x
3562                 return abs(x);
3563             } else if (expY > expX + 27) {
3564                 // x is neglectible with respect to y
3565                 return abs(y);
3566             } else {
3567 
3568                 // find an intermediate scale to avoid both overflow and underflow
3569                 final int middleExp = (expX + expY) / 2;
3570 
3571                 // scale parameters without losing precision
3572                 final double scaledX = scalb(x, -middleExp);
3573                 final double scaledY = scalb(y, -middleExp);
3574 
3575                 // compute scaled hypotenuse
3576                 final double scaledH = sqrt(scaledX * scaledX + scaledY * scaledY);
3577 
3578                 // remove scaling
3579                 return scalb(scaledH, middleExp);
3580 
3581             }
3582 
3583         }
3584     }
3585 
3586     /**
3587      * Computes the remainder as prescribed by the IEEE 754 standard.
3588      * The remainder value is mathematically equal to {@code x - y*n}
3589      * where {@code n} is the mathematical integer closest to the exact mathematical value
3590      * of the quotient {@code x/y}.
3591      * If two mathematical integers are equally close to {@code x/y} then
3592      * {@code n} is the integer that is even.
3593      * <p>
3594      * <ul>
3595      * <li>If either operand is NaN, the result is NaN.</li>
3596      * <li>If the result is not NaN, the sign of the result equals the sign of the dividend.</li>
3597      * <li>If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN.</li>
3598      * <li>If the dividend is finite and the divisor is an infinity, the result equals the dividend.</li>
3599      * <li>If the dividend is a zero and the divisor is finite, the result equals the dividend.</li>
3600      * </ul>
3601      * <p><b>Note:</b> this implementation currently delegates to {@link StrictMath#IEEEremainder}
3602      * @param dividend the number to be divided
3603      * @param divisor the number by which to divide
3604      * @return the remainder, rounded
3605      */
3606     public static double IEEEremainder(double dividend, double divisor) {
3607         return StrictMath.IEEEremainder(dividend, divisor); // TODO provide our own implementation
3608     }
3609 
3610     /**
3611      * Returns the first argument with the sign of the second argument.
3612      * A NaN {@code sign} argument is treated as positive.
3613      *
3614      * @param magnitude the value to return
3615      * @param sign the sign for the returned value
3616      * @return the magnitude with the same sign as the {@code sign} argument
3617      */
3618     public static double copySign(double magnitude, double sign){
3619         long m = Double.doubleToLongBits(magnitude);
3620         long s = Double.doubleToLongBits(sign);
3621         if ((m >= 0 && s >= 0) || (m < 0 && s < 0)) { // Sign is currently OK
3622             return magnitude;
3623         }
3624         return -magnitude; // flip sign
3625     }
3626 
3627     /**
3628      * Returns the first argument with the sign of the second argument.
3629      * A NaN {@code sign} argument is treated as positive.
3630      *
3631      * @param magnitude the value to return
3632      * @param sign the sign for the returned value
3633      * @return the magnitude with the same sign as the {@code sign} argument
3634      */
3635     public static float copySign(float magnitude, float sign){
3636         int m = Float.floatToIntBits(magnitude);
3637         int s = Float.floatToIntBits(sign);
3638         if ((m >= 0 && s >= 0) || (m < 0 && s < 0)) { // Sign is currently OK
3639             return magnitude;
3640         }
3641         return -magnitude; // flip sign
3642     }
3643 
3644     /**
3645      * Return the exponent of a double number, removing the bias.
3646      * <p>
3647      * For double numbers of the form 2<sup>x</sup>, the unbiased
3648      * exponent is exactly x.
3649      * </p>
3650      * @param d number from which exponent is requested
3651      * @return exponent for d in IEEE754 representation, without bias
3652      */
3653     public static int getExponent(final double d) {
3654         return (int) ((Double.doubleToLongBits(d) >>> 52) & 0x7ff) - 1023;
3655     }
3656 
3657     /**
3658      * Return the exponent of a float number, removing the bias.
3659      * <p>
3660      * For float numbers of the form 2<sup>x</sup>, the unbiased
3661      * exponent is exactly x.
3662      * </p>
3663      * @param f number from which exponent is requested
3664      * @return exponent for d in IEEE754 representation, without bias
3665      */
3666     public static int getExponent(final float f) {
3667         return ((Float.floatToIntBits(f) >>> 23) & 0xff) - 127;
3668     }
3669 
3670     /**
3671      * Print out contents of arrays, and check the length.
3672      * <p>used to generate the preset arrays originally.</p>
3673      * @param a unused
3674      */
3675     public static void main(String[] a) {
3676         PrintStream out = System.out;
3677         FastMathCalc.printarray(out, "EXP_INT_TABLE_A", EXP_INT_TABLE_LEN, ExpIntTable.EXP_INT_TABLE_A);
3678         FastMathCalc.printarray(out, "EXP_INT_TABLE_B", EXP_INT_TABLE_LEN, ExpIntTable.EXP_INT_TABLE_B);
3679         FastMathCalc.printarray(out, "EXP_FRAC_TABLE_A", EXP_FRAC_TABLE_LEN, ExpFracTable.EXP_FRAC_TABLE_A);
3680         FastMathCalc.printarray(out, "EXP_FRAC_TABLE_B", EXP_FRAC_TABLE_LEN, ExpFracTable.EXP_FRAC_TABLE_B);
3681         FastMathCalc.printarray(out, "LN_MANT",LN_MANT_LEN, lnMant.LN_MANT);
3682         FastMathCalc.printarray(out, "SINE_TABLE_A", SINE_TABLE_LEN, SINE_TABLE_A);
3683         FastMathCalc.printarray(out, "SINE_TABLE_B", SINE_TABLE_LEN, SINE_TABLE_B);
3684         FastMathCalc.printarray(out, "COSINE_TABLE_A", SINE_TABLE_LEN, COSINE_TABLE_A);
3685         FastMathCalc.printarray(out, "COSINE_TABLE_B", SINE_TABLE_LEN, COSINE_TABLE_B);
3686         FastMathCalc.printarray(out, "TANGENT_TABLE_A", SINE_TABLE_LEN, TANGENT_TABLE_A);
3687         FastMathCalc.printarray(out, "TANGENT_TABLE_B", SINE_TABLE_LEN, TANGENT_TABLE_B);
3688     }
3689 
3690     /** Enclose large data table in nested static class so it's only loaded on first access. */
3691     private static class ExpIntTable {
3692         /** Exponential evaluated at integer values,
3693          * exp(x) =  expIntTableA[x + EXP_INT_TABLE_MAX_INDEX] + expIntTableB[x+EXP_INT_TABLE_MAX_INDEX].
3694          */
3695         private static final double[] EXP_INT_TABLE_A;
3696         /** Exponential evaluated at integer values,
3697          * exp(x) =  expIntTableA[x + EXP_INT_TABLE_MAX_INDEX] + expIntTableB[x+EXP_INT_TABLE_MAX_INDEX]
3698          */
3699         private static final double[] EXP_INT_TABLE_B;
3700 
3701         static {
3702             if (RECOMPUTE_TABLES_AT_RUNTIME) {
3703                 EXP_INT_TABLE_A = new double[FastMath.EXP_INT_TABLE_LEN];
3704                 EXP_INT_TABLE_B = new double[FastMath.EXP_INT_TABLE_LEN];
3705 
3706                 final double tmp[] = new double[2];
3707                 final double recip[] = new double[2];
3708 
3709                 // Populate expIntTable
3710                 for (int i = 0; i < FastMath.EXP_INT_TABLE_MAX_INDEX; i++) {
3711                     FastMathCalc.expint(i, tmp);
3712                     EXP_INT_TABLE_A[i + FastMath.EXP_INT_TABLE_MAX_INDEX] = tmp[0];
3713                     EXP_INT_TABLE_B[i + FastMath.EXP_INT_TABLE_MAX_INDEX] = tmp[1];
3714 
3715                     if (i != 0) {
3716                         // Negative integer powers
3717                         FastMathCalc.splitReciprocal(tmp, recip);
3718                         EXP_INT_TABLE_A[FastMath.EXP_INT_TABLE_MAX_INDEX - i] = recip[0];
3719                         EXP_INT_TABLE_B[FastMath.EXP_INT_TABLE_MAX_INDEX - i] = recip[1];
3720                     }
3721                 }
3722             } else if (LOAD_RESOURCES) {
3723                 final double[][] expInt = FastMathResources.loadExpInt();
3724                 EXP_INT_TABLE_A = expInt[0];
3725                 EXP_INT_TABLE_B = expInt[1];
3726             } else {
3727                 EXP_INT_TABLE_A = FastMathLiteralArrays.loadExpIntA();
3728                 EXP_INT_TABLE_B = FastMathLiteralArrays.loadExpIntB();
3729             }
3730         }
3731     }
3732 
3733     /** Enclose large data table in nested static class so it's only loaded on first access. */
3734     private static class ExpFracTable {
3735         /** Exponential over the range of 0 - 1 in increments of 2^-10
3736          * exp(x/1024) =  expFracTableA[x] + expFracTableB[x].
3737          * 1024 = 2^10
3738          */
3739         private static final double[] EXP_FRAC_TABLE_A;
3740         /** Exponential over the range of 0 - 1 in increments of 2^-10
3741          * exp(x/1024) =  expFracTableA[x] + expFracTableB[x].
3742          */
3743         private static final double[] EXP_FRAC_TABLE_B;
3744 
3745         static {
3746             if (RECOMPUTE_TABLES_AT_RUNTIME) {
3747                 EXP_FRAC_TABLE_A = new double[FastMath.EXP_FRAC_TABLE_LEN];
3748                 EXP_FRAC_TABLE_B = new double[FastMath.EXP_FRAC_TABLE_LEN];
3749 
3750                 final double tmp[] = new double[2];
3751 
3752                 // Populate expFracTable
3753                 final double factor = 1d / (EXP_FRAC_TABLE_LEN - 1);
3754                 for (int i = 0; i < EXP_FRAC_TABLE_A.length; i++) {
3755                     FastMathCalc.slowexp(i * factor, tmp);
3756                     EXP_FRAC_TABLE_A[i] = tmp[0];
3757                     EXP_FRAC_TABLE_B[i] = tmp[1];
3758                 }
3759             } else if (LOAD_RESOURCES) {
3760                 final double[][] expFrac = FastMathResources.loadExpFrac();
3761                 EXP_FRAC_TABLE_A = expFrac[0];
3762                 EXP_FRAC_TABLE_B = expFrac[1];
3763             } else {
3764                 EXP_FRAC_TABLE_A = FastMathLiteralArrays.loadExpFracA();
3765                 EXP_FRAC_TABLE_B = FastMathLiteralArrays.loadExpFracB();
3766             }
3767         }
3768     }
3769 
3770     /** Enclose large data table in nested static class so it's only loaded on first access. */
3771     private static class lnMant {
3772         /** Extended precision logarithm table over the range 1 - 2 in increments of 2^-10. */
3773         private static final double[][] LN_MANT;
3774 
3775         static {
3776             if (RECOMPUTE_TABLES_AT_RUNTIME) {
3777                 LN_MANT = new double[FastMath.LN_MANT_LEN][];
3778 
3779                 // Populate lnMant table
3780                 for (int i = 0; i < LN_MANT.length; i++) {
3781                     final double d = Double.longBitsToDouble( (((long) i) << 42) | 0x3ff0000000000000L );
3782                     LN_MANT[i] = FastMathCalc.slowLog(d);
3783                 }
3784             } else if (LOAD_RESOURCES) {
3785                 LN_MANT = FastMathResources.loadLnMant();
3786             } else {
3787                 LN_MANT = FastMathLiteralArrays.loadLnMant();
3788             }
3789         }
3790     }
3791 }