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 * https://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
18 /*
19 * This is not the original file distributed by the Apache Software Foundation
20 * It has been modified by the Hipparchus project
21 */
22 package org.hipparchus.util;
23
24 import org.hipparchus.CalculusFieldElement;
25 import org.hipparchus.exception.LocalizedCoreFormats;
26 import org.hipparchus.exception.MathRuntimeException;
27
28 /**
29 * Faster, more accurate, portable alternative to {@link Math} and
30 * {@link StrictMath} for large scale computation.
31 * <p>
32 * FastMath is a drop-in replacement for both Math and StrictMath. This
33 * means that for any method in Math (say {@code Math.sin(x)} or
34 * {@code Math.cbrt(y)}), user can directly change the class and use the
35 * methods as is (using {@code FastMath.sin(x)} or {@code FastMath.cbrt(y)}
36 * in the previous example).
37 * <p>
38 * FastMath speed is achieved by relying heavily on optimizing compilers
39 * to native code present in many JVMs today and use of large tables.
40 * The larger tables are lazily initialized on first use, so that the setup
41 * time does not penalize methods that don't need them.
42 *
43 * <p>
44 * Note that FastMath is
45 * extensively used inside Hipparchus, so by calling some algorithms,
46 * the overhead when the the tables need to be initialized will occur
47 * regardless of the end-user calling FastMath methods directly or not.
48 * Performance figures for a specific JVM and hardware can be evaluated by
49 * running the FastMathTestPerformance tests in the test directory of the source
50 * distribution.
51 * <p>
52 * FastMath accuracy should be mostly independent of the JVM as it relies only
53 * on IEEE-754 basic operations and on embedded tables. Almost all operations
54 * are accurate to about 0.5 ulp throughout the domain range. This statement,
55 * of course is only a rough global observed behavior, it is <em>not</em> a
56 * guarantee for <em>every</em> double numbers input (see William Kahan's <a
57 * href="http://en.wikipedia.org/wiki/Rounding#The_table-maker.27s_dilemma">Table
58 * Maker's Dilemma</a>).
59 * <p>
60 * FastMath additionally implements the following methods not found in Math/StrictMath:
61 * <ul>
62 * <li>{@link #asinh(double)}</li>
63 * <li>{@link #acosh(double)}</li>
64 * <li>{@link #atanh(double)}</li>
65 * </ul>
66 * The following methods are found in Math/StrictMath since 1.6 only, they are provided
67 * by FastMath even in 1.5 Java virtual machines
68 * <ul>
69 * <li>{@link #copySign(double, double)}</li>
70 * <li>{@link #getExponent(double)}</li>
71 * <li>{@link #nextAfter(double,double)}</li>
72 * <li>{@link #nextUp(double)}</li>
73 * <li>{@link #scalb(double, int)}</li>
74 * <li>{@link #copySign(float, float)}</li>
75 * <li>{@link #getExponent(float)}</li>
76 * <li>{@link #nextAfter(float,double)}</li>
77 * <li>{@link #nextUp(float)}</li>
78 * <li>{@link #scalb(float, int)}</li>
79 * </ul>
80 */
81 public class FastMath {
82
83 /** Archimede's constant PI, ratio of circle circumference to diameter. */
84 public static final double PI = 105414357.0 / 33554432.0 + 1.984187159361080883e-9;
85
86 /** Double Archimede's constant, ratio of circle circumference to radius.
87 * @since 4.1
88 */
89 public static final double TAU = 1686629713.0 / 268435456.0 + 2.43084020260247704e-10;
90
91 /** Napier's constant e, base of the natural logarithm. */
92 public static final double E = 2850325.0 / 1048576.0 + 8.254840070411028747e-8;
93
94 /** Index of exp(0) in the array of integer exponentials. */
95 static final int EXP_INT_TABLE_MAX_INDEX = 750;
96 /** Length of the array of integer exponentials. */
97 static final int EXP_INT_TABLE_LEN = EXP_INT_TABLE_MAX_INDEX * 2;
98 /** Logarithm table length. */
99 static final int LN_MANT_LEN = 1024;
100 /** Exponential fractions table length. */
101 static final int EXP_FRAC_TABLE_LEN = 1025; // 0, 1/1024, ... 1024/1024
102
103 /** StrictMath.log(Double.MAX_VALUE): {@value} */
104 private static final double LOG_MAX_VALUE = StrictMath.log(Double.MAX_VALUE);
105
106 /** Indicator for tables initialization.
107 * <p>
108 * This compile-time constant should be set to true only if one explicitly
109 * wants to compute the tables at class loading time instead of using the
110 * already computed ones provided as literal arrays below.
111 * </p>
112 */
113 private static final boolean RECOMPUTE_TABLES_AT_RUNTIME = false;
114
115 /** log(2) (high bits). */
116 private static final double LN_2_A = 0.693147063255310059;
117
118 /** log(2) (low bits). */
119 private static final double LN_2_B = 1.17304635250823482e-7;
120
121 /** Coefficients for log, when input 0.99 < x < 1.01. */
122 private static final double[][] LN_QUICK_COEF = {
123 {1.0, 5.669184079525E-24},
124 {-0.25, -0.25},
125 {0.3333333134651184, 1.986821492305628E-8},
126 {-0.25, -6.663542893624021E-14},
127 {0.19999998807907104, 1.1921056801463227E-8},
128 {-0.1666666567325592, -7.800414592973399E-9},
129 {0.1428571343421936, 5.650007086920087E-9},
130 {-0.12502530217170715, -7.44321345601866E-11},
131 {0.11113807559013367, 9.219544613762692E-9},
132 };
133
134 /** Coefficients for log in the range of 1.0 < x < 1.0 + 2^-10. */
135 private static final double[][] LN_HI_PREC_COEF = {
136 {1.0, -6.032174644509064E-23},
137 {-0.25, -0.25},
138 {0.3333333134651184, 1.9868161777724352E-8},
139 {-0.2499999701976776, -2.957007209750105E-8},
140 {0.19999954104423523, 1.5830993332061267E-10},
141 {-0.16624879837036133, -2.6033824355191673E-8}
142 };
143
144 /* Sine, Cosine, Tangent tables are for 0, 1/8, 2/8, ... 13/8 = PI/2 approx. */
145
146 /** Sine table (high bits). */
147 private static final double[] SINE_TABLE_A =
148 {
149 +0.0d,
150 +0.1246747374534607d,
151 +0.24740394949913025d,
152 +0.366272509098053d,
153 +0.4794255495071411d,
154 +0.5850973129272461d,
155 +0.6816387176513672d,
156 +0.7675435543060303d,
157 +0.8414709568023682d,
158 +0.902267575263977d,
159 +0.9489846229553223d,
160 +0.9808930158615112d,
161 +0.9974949359893799d,
162 +0.9985313415527344d,
163 };
164
165 /** Sine table (low bits). */
166 private static final double[] SINE_TABLE_B =
167 {
168 +0.0d,
169 -4.068233003401932E-9d,
170 +9.755392680573412E-9d,
171 +1.9987994582857286E-8d,
172 -1.0902938113007961E-8d,
173 -3.9986783938944604E-8d,
174 +4.23719669792332E-8d,
175 -5.207000323380292E-8d,
176 +2.800552834259E-8d,
177 +1.883511811213715E-8d,
178 -3.5997360512765566E-9d,
179 +4.116164446561962E-8d,
180 +5.0614674548127384E-8d,
181 -1.0129027912496858E-9d,
182 };
183
184 /** Cosine table (high bits). */
185 private static final double[] COSINE_TABLE_A =
186 {
187 +1.0d,
188 +0.9921976327896118d,
189 +0.9689123630523682d,
190 +0.9305076599121094d,
191 +0.8775825500488281d,
192 +0.8109631538391113d,
193 +0.7316888570785522d,
194 +0.6409968137741089d,
195 +0.5403022766113281d,
196 +0.4311765432357788d,
197 +0.3153223395347595d,
198 +0.19454771280288696d,
199 +0.07073719799518585d,
200 -0.05417713522911072d,
201 };
202
203 /** Cosine table (low bits). */
204 private static final double[] COSINE_TABLE_B =
205 {
206 +0.0d,
207 +3.4439717236742845E-8d,
208 +5.865827662008209E-8d,
209 -3.7999795083850525E-8d,
210 +1.184154459111628E-8d,
211 -3.43338934259355E-8d,
212 +1.1795268640216787E-8d,
213 +4.438921624363781E-8d,
214 +2.925681159240093E-8d,
215 -2.6437112632041807E-8d,
216 +2.2860509143963117E-8d,
217 -4.813899778443457E-9d,
218 +3.6725170580355583E-9d,
219 +2.0217439756338078E-10d,
220 };
221
222
223 /** Tangent table, used by atan() (high bits). */
224 private static final double[] TANGENT_TABLE_A =
225 {
226 +0.0d,
227 +0.1256551444530487d,
228 +0.25534194707870483d,
229 +0.3936265707015991d,
230 +0.5463024377822876d,
231 +0.7214844226837158d,
232 +0.9315965175628662d,
233 +1.1974215507507324d,
234 +1.5574076175689697d,
235 +2.092571258544922d,
236 +3.0095696449279785d,
237 +5.041914939880371d,
238 +14.101419448852539d,
239 -18.430862426757812d,
240 };
241
242 /** Tangent table, used by atan() (low bits). */
243 private static final double[] TANGENT_TABLE_B =
244 {
245 +0.0d,
246 -7.877917738262007E-9d,
247 -2.5857668567479893E-8d,
248 +5.2240336371356666E-9d,
249 +5.206150291559893E-8d,
250 +1.8307188599677033E-8d,
251 -5.7618793749770706E-8d,
252 +7.848361555046424E-8d,
253 +1.0708593250394448E-7d,
254 +1.7827257129423813E-8d,
255 +2.893485277253286E-8d,
256 +3.1660099222737955E-7d,
257 +4.983191803254889E-7d,
258 -3.356118100840571E-7d,
259 };
260
261 /** Bits of 1/(2*pi), need for reducePayneHanek(). */
262 private static final long[] RECIP_2PI = {
263 (0x28be60dbL << 32) | 0x9391054aL,
264 (0x7f09d5f4L << 32) | 0x7d4d3770L,
265 (0x36d8a566L << 32) | 0x4f10e410L,
266 (0x7f9458eaL << 32) | 0xf7aef158L,
267 (0x6dc91b8eL << 32) | 0x909374b8L,
268 (0x01924bbaL << 32) | 0x82746487L,
269 (0x3f877ac7L << 32) | 0x2c4a69cfL,
270 (0xba208d7dL << 32) | 0x4baed121L,
271 (0x3a671c09L << 32) | 0xad17df90L,
272 (0x4e64758eL << 32) | 0x60d4ce7dL,
273 (0x272117e2L << 32) | 0xef7e4a0eL,
274 (0xc7fe25ffL << 32) | 0xf7816603L,
275 (0xfbcbc462L << 32) | 0xd6829b47L,
276 (0xdb4d9fb3L << 32) | 0xc9f2c26dL,
277 (0xd3d18fd9L << 32) | 0xa797fa8bL,
278 (0x5d49eeb1L << 32) | 0xfaf97c5eL,
279 (0xcf41ce7dL << 32) | 0xe294a4baL,
280 0x9afed7ecL << 32 };
281
282 /** Bits of pi/4, need for reducePayneHanek(). */
283 private static final long[] PI_O_4_BITS = {
284 (0xc90fdaa2L << 32) | 0x2168c234L,
285 (0xc4c6628bL << 32) | 0x80dc1cd1L };
286
287 /** Eighths.
288 * This is used by sinQ, because its faster to do a table lookup than
289 * a multiply in this time-critical routine
290 */
291 private static final double[]
292 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};
293
294 /** Table of 2^((n+2)/3) */
295 private static final double[] CBRTTWO = { 0.6299605249474366,
296 0.7937005259840998,
297 1.0,
298 1.2599210498948732,
299 1.5874010519681994 };
300
301 /*
302 * There are 52 bits in the mantissa of a double.
303 * For additional precision, the code splits double numbers into two parts,
304 * by clearing the low order 30 bits if possible, and then performs the arithmetic
305 * on each half separately.
306 */
307
308 /**
309 * 0x40000000 - used to split a double into two parts, both with the low order bits cleared.
310 * Equivalent to 2^30.
311 */
312 private static final long HEX_40000000 = 0x40000000L; // 1073741824L
313
314 /** Mask used to clear low order 30 bits */
315 private static final long MASK_30BITS = -1L - (HEX_40000000 -1); // 0xFFFFFFFFC0000000L;
316
317 /** Mask used to clear the non-sign part of an int. */
318 private static final int MASK_NON_SIGN_INT = 0x7fffffff;
319
320 /** Mask used to clear the non-sign part of a long. */
321 private static final long MASK_NON_SIGN_LONG = 0x7fffffffffffffffL;
322
323 /** Mask used to extract exponent from double bits. */
324 private static final long MASK_DOUBLE_EXPONENT = 0x7ff0000000000000L;
325
326 /** Mask used to extract mantissa from double bits. */
327 private static final long MASK_DOUBLE_MANTISSA = 0x000fffffffffffffL;
328
329 /** Mask used to add implicit high order bit for normalized double. */
330 private static final long IMPLICIT_HIGH_BIT = 0x0010000000000000L;
331
332 /** 2^52 - double numbers this large must be integral (no fraction) or NaN or Infinite */
333 private static final double TWO_POWER_52 = 4503599627370496.0;
334
335 /** Constant: {@value}. */
336 private static final double F_1_3 = 1d / 3d;
337 /** Constant: {@value}. */
338 private static final double F_1_5 = 1d / 5d;
339 /** Constant: {@value}. */
340 private static final double F_1_7 = 1d / 7d;
341 /** Constant: {@value}. */
342 private static final double F_1_9 = 1d / 9d;
343 /** Constant: {@value}. */
344 private static final double F_1_11 = 1d / 11d;
345 /** Constant: {@value}. */
346 private static final double F_1_13 = 1d / 13d;
347 /** Constant: {@value}. */
348 private static final double F_1_15 = 1d / 15d;
349 /** Constant: {@value}. */
350 private static final double F_1_17 = 1d / 17d;
351 /** Constant: {@value}. */
352 private static final double F_3_4 = 3d / 4d;
353 /** Constant: {@value}. */
354 private static final double F_15_16 = 15d / 16d;
355 /** Constant: {@value}. */
356 private static final double F_13_14 = 13d / 14d;
357 /** Constant: {@value}. */
358 private static final double F_11_12 = 11d / 12d;
359 /** Constant: {@value}. */
360 private static final double F_9_10 = 9d / 10d;
361 /** Constant: {@value}. */
362 private static final double F_7_8 = 7d / 8d;
363 /** Constant: {@value}. */
364 private static final double F_5_6 = 5d / 6d;
365 /** Constant: {@value}. */
366 private static final double F_1_2 = 1d / 2d;
367 /** Constant: {@value}. */
368 private static final double F_1_4 = 1d / 4d;
369
370 /**
371 * Private Constructor
372 */
373 private FastMath() {}
374
375 // Generic helper methods
376
377 /**
378 * Get the high order bits from the mantissa.
379 * Equivalent to adding and subtracting HEX_40000 but also works for very large numbers
380 *
381 * @param d the value to split
382 * @return the high order part of the mantissa
383 */
384 private static double doubleHighPart(double d) {
385 if (d > -Precision.SAFE_MIN && d < Precision.SAFE_MIN){
386 return d; // These are un-normalised - don't try to convert
387 }
388 long xl = Double.doubleToRawLongBits(d); // can take raw bits because just gonna convert it back
389 xl &= MASK_30BITS; // Drop low order bits
390 return Double.longBitsToDouble(xl);
391 }
392
393 /** Compute the square root of a number.
394 * <p><b>Note:</b> this implementation currently delegates to {@link Math#sqrt}
395 * @param a number on which evaluation is done
396 * @return square root of a
397 */
398 public static double sqrt(final double a) {
399 return Math.sqrt(a);
400 }
401
402 /** Compute the hyperbolic cosine of a number.
403 * @param x number on which evaluation is done
404 * @return hyperbolic cosine of x
405 */
406 public static double cosh(double x) {
407 if (Double.isNaN(x)) {
408 return x;
409 }
410
411 // cosh[z] = (exp(z) + exp(-z))/2
412
413 // for numbers with magnitude 20 or so,
414 // exp(-z) can be ignored in comparison with exp(z)
415
416 if (x > 20) {
417 if (x >= LOG_MAX_VALUE) {
418 // Avoid overflow (MATH-905).
419 final double t = exp(0.5 * x);
420 return (0.5 * t) * t;
421 } else {
422 return 0.5 * exp(x);
423 }
424 } else if (x < -20) {
425 if (x <= -LOG_MAX_VALUE) {
426 // Avoid overflow (MATH-905).
427 final double t = exp(-0.5 * x);
428 return (0.5 * t) * t;
429 } else {
430 return 0.5 * exp(-x);
431 }
432 }
433
434 final double[] hiPrec = new double[2];
435 if (x < 0.0) {
436 x = -x;
437 }
438 exp(x, 0.0, hiPrec);
439
440 double ya = hiPrec[0] + hiPrec[1];
441 double yb = -(ya - hiPrec[0] - hiPrec[1]);
442
443 double temp = ya * HEX_40000000;
444 double yaa = ya + temp - temp;
445 double yab = ya - yaa;
446
447 // recip = 1/y
448 double recip = 1.0/ya;
449 temp = recip * HEX_40000000;
450 double recipa = recip + temp - temp;
451 double recipb = recip - recipa;
452
453 // Correct for rounding in division
454 recipb += (1.0 - yaa*recipa - yaa*recipb - yab*recipa - yab*recipb) * recip;
455 // Account for yb
456 recipb += -yb * recip * recip;
457
458 // y = y + 1/y
459 temp = ya + recipa;
460 yb += -(temp - ya - recipa);
461 ya = temp;
462 temp = ya + recipb;
463 yb += -(temp - ya - recipb);
464 ya = temp;
465
466 double result = ya + yb;
467 result *= 0.5;
468 return result;
469 }
470
471 /** Compute the hyperbolic sine of a number.
472 * @param x number on which evaluation is done
473 * @return hyperbolic sine of x
474 */
475 public static double sinh(double x) {
476 boolean negate = false;
477 if (Double.isNaN(x)) {
478 return x;
479 }
480
481 // sinh[z] = (exp(z) - exp(-z) / 2
482
483 // for values of z larger than about 20,
484 // exp(-z) can be ignored in comparison with exp(z)
485
486 if (x > 20) {
487 if (x >= LOG_MAX_VALUE) {
488 // Avoid overflow (MATH-905).
489 final double t = exp(0.5 * x);
490 return (0.5 * t) * t;
491 } else {
492 return 0.5 * exp(x);
493 }
494 } else if (x < -20) {
495 if (x <= -LOG_MAX_VALUE) {
496 // Avoid overflow (MATH-905).
497 final double t = exp(-0.5 * x);
498 return (-0.5 * t) * t;
499 } else {
500 return -0.5 * exp(-x);
501 }
502 }
503
504 if (x == 0) {
505 return x;
506 }
507
508 if (x < 0.0) {
509 x = -x;
510 negate = true;
511 }
512
513 double[] hiPrec = new double[2];
514 double result;
515
516 if (x > 0.25) {
517 exp(x, 0.0, hiPrec);
518
519 double ya = hiPrec[0] + hiPrec[1];
520 double yb = -(ya - hiPrec[0] - hiPrec[1]);
521
522 double temp = ya * HEX_40000000;
523 double yaa = ya + temp - temp;
524 double yab = ya - yaa;
525
526 // recip = 1/y
527 double recip = 1.0/ya;
528 temp = recip * HEX_40000000;
529 double recipa = recip + temp - temp;
530 double recipb = recip - recipa;
531
532 // Correct for rounding in division
533 recipb += (1.0 - yaa*recipa - yaa*recipb - yab*recipa - yab*recipb) * recip;
534 // Account for yb
535 recipb += -yb * recip * recip;
536
537 recipa = -recipa;
538 recipb = -recipb;
539
540 // y = y - 1/y
541 temp = ya + recipa;
542 yb += -(temp - ya - recipa);
543 ya = temp;
544 temp = ya + recipb;
545 yb += -(temp - ya - recipb);
546 ya = temp;
547
548 result = ya + yb;
549 result *= 0.5;
550 } else {
551 expm1(x, hiPrec);
552
553 double ya = hiPrec[0] + hiPrec[1];
554 double yb = -(ya - hiPrec[0] - hiPrec[1]);
555
556 /* Compute expm1(-x) = -expm1(x) / (expm1(x) + 1) */
557 double denom = 1.0 + ya;
558 double denomr = 1.0 / denom;
559 double denomb = -(denom - 1.0 - ya) + yb;
560 double ratio = ya * denomr;
561 double temp = ratio * HEX_40000000;
562 double ra = ratio + temp - temp;
563 double rb = ratio - ra;
564
565 temp = denom * HEX_40000000;
566 double za = denom + temp - temp;
567 double zb = denom - za;
568
569 rb += (ya - za*ra - za*rb - zb*ra - zb*rb) * denomr;
570
571 // Adjust for yb
572 rb += yb*denomr; // numerator
573 rb += -ya * denomb * denomr * denomr; // denominator
574
575 // y = y - 1/y
576 temp = ya + ra;
577 yb += -(temp - ya - ra);
578 ya = temp;
579 temp = ya + rb;
580 yb += -(temp - ya - rb);
581 ya = temp;
582
583 result = ya + yb;
584 result *= 0.5;
585 }
586
587 if (negate) {
588 result = -result;
589 }
590
591 return result;
592 }
593
594 /**
595 * Combined hyperbolic sine and hyperbolic cosine function.
596 *
597 * @param x Argument.
598 * @return [sinh(x), cosh(x)]
599 */
600 public static SinhCosh sinhCosh(double x) {
601 boolean negate = false;
602 if (Double.isNaN(x)) {
603 return new SinhCosh(x, x);
604 }
605
606 // sinh[z] = (exp(z) - exp(-z) / 2
607 // cosh[z] = (exp(z) + exp(-z))/2
608
609 // for values of z larger than about 20,
610 // exp(-z) can be ignored in comparison with exp(z)
611
612 if (x > 20) {
613 final double e;
614 if (x >= LOG_MAX_VALUE) {
615 // Avoid overflow (MATH-905).
616 final double t = exp(0.5 * x);
617 e = (0.5 * t) * t;
618 } else {
619 e = 0.5 * exp(x);
620 }
621 return new SinhCosh(e, e);
622 } else if (x < -20) {
623 final double e;
624 if (x <= -LOG_MAX_VALUE) {
625 // Avoid overflow (MATH-905).
626 final double t = exp(-0.5 * x);
627 e = (-0.5 * t) * t;
628 } else {
629 e = -0.5 * exp(-x);
630 }
631 return new SinhCosh(e, -e);
632 }
633
634 if (x == 0) {
635 return new SinhCosh(x, 1.0);
636 }
637
638 if (x < 0.0) {
639 x = -x;
640 negate = true;
641 }
642
643 double[] hiPrec = new double[2];
644 double resultM;
645 double resultP;
646
647 if (x > 0.25) {
648 exp(x, 0.0, hiPrec);
649
650 final double ya = hiPrec[0] + hiPrec[1];
651 final double yb = -(ya - hiPrec[0] - hiPrec[1]);
652
653 double temp = ya * HEX_40000000;
654 double yaa = ya + temp - temp;
655 double yab = ya - yaa;
656
657 // recip = 1/y
658 double recip = 1.0/ya;
659 temp = recip * HEX_40000000;
660 double recipa = recip + temp - temp;
661 double recipb = recip - recipa;
662
663 // Correct for rounding in division
664 recipb += (1.0 - yaa*recipa - yaa*recipb - yab*recipa - yab*recipb) * recip;
665 // Account for yb
666 recipb += -yb * recip * recip;
667
668 // y = y - 1/y
669 temp = ya - recipa;
670 double ybM = yb - (temp - ya + recipa);
671 double yaM = temp;
672 temp = yaM - recipb;
673 ybM += -(temp - yaM + recipb);
674 yaM = temp;
675 resultM = yaM + ybM;
676 resultM *= 0.5;
677
678 // y = y + 1/y
679 temp = ya + recipa;
680 double ybP = yb - (temp - ya - recipa);
681 double yaP = temp;
682 temp = yaP + recipb;
683 ybP += -(temp - yaP - recipb);
684 yaP = temp;
685 resultP = yaP + ybP;
686 resultP *= 0.5;
687
688 } else {
689 expm1(x, hiPrec);
690
691 final double ya = hiPrec[0] + hiPrec[1];
692 final double yb = -(ya - hiPrec[0] - hiPrec[1]);
693
694 /* Compute expm1(-x) = -expm1(x) / (expm1(x) + 1) */
695 double denom = 1.0 + ya;
696 double denomr = 1.0 / denom;
697 double denomb = -(denom - 1.0 - ya) + yb;
698 double ratio = ya * denomr;
699 double temp = ratio * HEX_40000000;
700 double ra = ratio + temp - temp;
701 double rb = ratio - ra;
702
703 temp = denom * HEX_40000000;
704 double za = denom + temp - temp;
705 double zb = denom - za;
706
707 rb += (ya - za*ra - za*rb - zb*ra - zb*rb) * denomr;
708
709 // Adjust for yb
710 rb += yb*denomr; // numerator
711 rb += -ya * denomb * denomr * denomr; // denominator
712
713 // y = y - 1/y
714 temp = ya + ra;
715 double ybM = yb - (temp - ya - ra);
716 double yaM = temp;
717 temp = yaM + rb;
718 ybM += -(temp - yaM - rb);
719 yaM = temp;
720 resultM = yaM + ybM;
721 resultM *= 0.5;
722
723 // y = y + 1/y + 2
724 temp = ya - ra;
725 double ybP = yb - (temp - ya + ra);
726 double yaP = temp;
727 temp = yaP - rb;
728 ybP += -(temp - yaP + rb);
729 yaP = temp;
730 resultP = yaP + ybP + 2;
731 resultP *= 0.5;
732 }
733
734 if (negate) {
735 resultM = -resultM;
736 }
737
738 return new SinhCosh(resultM, resultP);
739
740 }
741
742 /**
743 * Combined hyperbolic sine and hyperbolic cosine function.
744 *
745 * @param x Argument.
746 * @param <T> the type of the field element
747 * @return [sinh(x), cosh(x)]
748 */
749 public static <T extends CalculusFieldElement<T>> FieldSinhCosh<T> sinhCosh(T x) {
750 return x.sinhCosh();
751 }
752
753 /** Compute the hyperbolic tangent of a number.
754 * @param x number on which evaluation is done
755 * @return hyperbolic tangent of x
756 */
757 public static double tanh(double x) {
758 boolean negate = false;
759
760 if (Double.isNaN(x)) {
761 return x;
762 }
763
764 // tanh[z] = sinh[z] / cosh[z]
765 // = (exp(z) - exp(-z)) / (exp(z) + exp(-z))
766 // = (exp(2x) - 1) / (exp(2x) + 1)
767
768 // for magnitude > 20, sinh[z] == cosh[z] in double precision
769
770 if (x > 20.0) {
771 return 1.0;
772 }
773
774 if (x < -20) {
775 return -1.0;
776 }
777
778 if (x == 0) {
779 return x;
780 }
781
782 if (x < 0.0) {
783 x = -x;
784 negate = true;
785 }
786
787 double result;
788 if (x >= 0.5) {
789 double[] hiPrec = new double[2];
790 // tanh(x) = (exp(2x) - 1) / (exp(2x) + 1)
791 exp(x*2.0, 0.0, hiPrec);
792
793 double ya = hiPrec[0] + hiPrec[1];
794 double yb = -(ya - hiPrec[0] - hiPrec[1]);
795
796 /* Numerator */
797 double na = -1.0 + ya;
798 double nb = -(na + 1.0 - ya);
799 double temp = na + yb;
800 nb += -(temp - na - yb);
801 na = temp;
802
803 /* Denominator */
804 double da = 1.0 + ya;
805 double db = -(da - 1.0 - ya);
806 temp = da + yb;
807 db += -(temp - da - yb);
808 da = temp;
809
810 temp = da * HEX_40000000;
811 double daa = da + temp - temp;
812 double dab = da - daa;
813
814 // ratio = na/da
815 double ratio = na/da;
816 temp = ratio * HEX_40000000;
817 double ratioa = ratio + temp - temp;
818 double ratiob = ratio - ratioa;
819
820 // Correct for rounding in division
821 ratiob += (na - daa*ratioa - daa*ratiob - dab*ratioa - dab*ratiob) / da;
822
823 // Account for nb
824 ratiob += nb / da;
825 // Account for db
826 ratiob += -db * na / da / da;
827
828 result = ratioa + ratiob;
829 }
830 else {
831 double[] hiPrec = new double[2];
832 // tanh(x) = expm1(2x) / (expm1(2x) + 2)
833 expm1(x*2.0, hiPrec);
834
835 double ya = hiPrec[0] + hiPrec[1];
836 double yb = -(ya - hiPrec[0] - hiPrec[1]);
837
838 /* Numerator */
839 double na = ya;
840 double nb = yb;
841
842 /* Denominator */
843 double da = 2.0 + ya;
844 double db = -(da - 2.0 - ya);
845 double temp = da + yb;
846 db += -(temp - da - yb);
847 da = temp;
848
849 temp = da * HEX_40000000;
850 double daa = da + temp - temp;
851 double dab = da - daa;
852
853 // ratio = na/da
854 double ratio = na/da;
855 temp = ratio * HEX_40000000;
856 double ratioa = ratio + temp - temp;
857 double ratiob = ratio - ratioa;
858
859 // Correct for rounding in division
860 ratiob += (na - daa*ratioa - daa*ratiob - dab*ratioa - dab*ratiob) / da;
861
862 // Account for nb
863 ratiob += nb / da;
864 // Account for db
865 ratiob += -db * na / da / da;
866
867 result = ratioa + ratiob;
868 }
869
870 if (negate) {
871 result = -result;
872 }
873
874 return result;
875 }
876
877 /** Compute the inverse hyperbolic cosine of a number.
878 * @param a number on which evaluation is done
879 * @return inverse hyperbolic cosine of a
880 */
881 public static double acosh(final double a) {
882 return log(a + sqrt(a * a - 1));
883 }
884
885 /** Compute the inverse hyperbolic sine of a number.
886 * @param a number on which evaluation is done
887 * @return inverse hyperbolic sine of a
888 */
889 public static double asinh(double a) {
890 boolean negative = false;
891 if (a < 0) {
892 negative = true;
893 a = -a;
894 }
895
896 double absAsinh;
897 if (a > 0.167) {
898 absAsinh = log(sqrt(a * a + 1) + a);
899 } else {
900 final double a2 = a * a;
901 if (a > 0.097) {
902 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);
903 } else if (a > 0.036) {
904 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);
905 } else if (a > 0.0036) {
906 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);
907 } else {
908 absAsinh = a * (1 - a2 * (F_1_3 - a2 * F_1_5 * F_3_4) * F_1_2);
909 }
910 }
911
912 return negative ? -absAsinh : absAsinh;
913 }
914
915 /** Compute the inverse hyperbolic tangent of a number.
916 * @param a number on which evaluation is done
917 * @return inverse hyperbolic tangent of a
918 */
919 public static double atanh(double a) {
920 boolean negative = false;
921 if (a < 0) {
922 negative = true;
923 a = -a;
924 }
925
926 double absAtanh;
927 if (a > 0.15) {
928 absAtanh = 0.5 * log((1 + a) / (1 - a));
929 } else {
930 final double a2 = a * a;
931 if (a > 0.087) {
932 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))))))));
933 } else if (a > 0.031) {
934 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))))));
935 } else if (a > 0.003) {
936 absAtanh = a * (1 + a2 * (F_1_3 + a2 * (F_1_5 + a2 * (F_1_7 + a2 * F_1_9))));
937 } else {
938 absAtanh = a * (1 + a2 * (F_1_3 + a2 * F_1_5));
939 }
940 }
941
942 return negative ? -absAtanh : absAtanh;
943 }
944
945 /** Compute the signum of a number.
946 * The signum is -1 for negative numbers, +1 for positive numbers and 0 otherwise
947 * @param a number on which evaluation is done
948 * @return -1.0, -0.0, +0.0, +1.0 or NaN depending on sign of a
949 */
950 public static double signum(final double a) {
951 return (a < 0.0) ? -1.0 : ((a > 0.0) ? 1.0 : a); // return +0.0/-0.0/NaN depending on a
952 }
953
954 /** Compute the signum of a number.
955 * The signum is -1 for negative numbers, +1 for positive numbers and 0 otherwise
956 * @param a number on which evaluation is done
957 * @return -1.0, -0.0, +0.0, +1.0 or NaN depending on sign of a
958 */
959 public static float signum(final float a) {
960 return (a < 0.0f) ? -1.0f : ((a > 0.0f) ? 1.0f : a); // return +0.0/-0.0/NaN depending on a
961 }
962
963 /** Compute next number towards positive infinity.
964 * @param a number to which neighbor should be computed
965 * @return neighbor of a towards positive infinity
966 */
967 public static double nextUp(final double a) {
968 return nextAfter(a, Double.POSITIVE_INFINITY);
969 }
970
971 /** Compute next number towards positive infinity.
972 * @param a number to which neighbor should be computed
973 * @return neighbor of a towards positive infinity
974 */
975 public static float nextUp(final float a) {
976 return nextAfter(a, Float.POSITIVE_INFINITY);
977 }
978
979 /** Compute next number towards negative infinity.
980 * @param a number to which neighbor should be computed
981 * @return neighbor of a towards negative infinity
982 */
983 public static double nextDown(final double a) {
984 return nextAfter(a, Double.NEGATIVE_INFINITY);
985 }
986
987 /** Compute next number towards negative infinity.
988 * @param a number to which neighbor should be computed
989 * @return neighbor of a towards negative infinity
990 */
991 public static float nextDown(final float a) {
992 return nextAfter(a, Float.NEGATIVE_INFINITY);
993 }
994
995 /** Clamp a value within an interval.
996 * @param value value to clamp
997 * @param inf lower bound of the clamping interval
998 * @param sup upper bound of the clamping interval
999 * @return value clamped within [inf; sup], or value if already within bounds.
1000 * @since 3.0
1001 */
1002 public static int clamp(final int value, final int inf, final int sup) {
1003 return max(inf, min(value, sup));
1004 }
1005
1006 /** Clamp a value within an interval.
1007 * @param value value to clamp
1008 * @param inf lower bound of the clamping interval
1009 * @param sup upper bound of the clamping interval
1010 * @return value clamped within [inf; sup], or value if already within bounds.
1011 * @since 3.0
1012 */
1013 public static long clamp(final long value, final long inf, final long sup) {
1014 return max(inf, min(value, sup));
1015 }
1016
1017 /** Clamp a value within an interval.
1018 * @param value value to clamp
1019 * @param inf lower bound of the clamping interval
1020 * @param sup upper bound of the clamping interval
1021 * @return value clamped within [inf; sup], or value if already within bounds.
1022 * @since 3.0
1023 */
1024 public static int clamp(final long value, final int inf, final int sup) {
1025 return (int) max(inf, min(value, sup));
1026 }
1027
1028 /** Clamp a value within an interval.
1029 * <p>
1030 * This method assumes -0.0 is below +0.0
1031 * </p>
1032 * @param value value to clamp
1033 * @param inf lower bound of the clamping interval
1034 * @param sup upper bound of the clamping interval
1035 * @return value clamped within [inf; sup], or value if already within bounds.
1036 * @since 3.0
1037 */
1038 public static float clamp(final float value, final float inf, final float sup) {
1039 return max(inf, min(value, sup));
1040 }
1041
1042 /** Clamp a value within an interval.
1043 * <p>
1044 * This method assumes -0.0 is below +0.0
1045 * </p>
1046 * @param value value to clamp
1047 * @param inf lower bound of the clamping interval
1048 * @param sup upper bound of the clamping interval
1049 * @return value clamped within [inf; sup], or value if already within bounds.
1050 * @since 3.0
1051 */
1052 public static double clamp(final double value, final double inf, final double sup) {
1053 return max(inf, min(value, sup));
1054 }
1055
1056 /** Returns a pseudo-random number between 0.0 and 1.0.
1057 * <p><b>Note:</b> this implementation currently delegates to {@link Math#random}
1058 * @return a random number between 0.0 and 1.0
1059 */
1060 public static double random() {
1061 return Math.random();
1062 }
1063
1064 /**
1065 * Exponential function.
1066 *
1067 * Computes exp(x), function result is nearly rounded. It will be correctly
1068 * rounded to the theoretical value for 99.9% of input values, otherwise it will
1069 * have a 1 ULP error.
1070 *
1071 * Method:
1072 * Lookup intVal = exp(int(x))
1073 * Lookup fracVal = exp(int(x-int(x) / 1024.0) * 1024.0 );
1074 * Compute z as the exponential of the remaining bits by a polynomial minus one
1075 * exp(x) = intVal * fracVal * (1 + z)
1076 *
1077 * Accuracy:
1078 * Calculation is done with 63 bits of precision, so result should be correctly
1079 * rounded for 99.9% of input values, with less than 1 ULP error otherwise.
1080 *
1081 * @param x a double
1082 * @return double e<sup>x</sup>
1083 */
1084 public static double exp(double x) {
1085 return exp(x, 0.0, null);
1086 }
1087
1088 /**
1089 * Internal helper method for computing a high-precision exponential in
1090 *
1091 * <ul>
1092 * <li>{@link #sinh(double)},</li>
1093 * <li>{@link #cosh(double)},</li>
1094 * <li>{@link #tanh(double)}, and</li>
1095 * <li>{@link #sinhCosh(double)}</li>
1096 * </ul>
1097 *
1098 * @param x original argument of the exponential function
1099 * @param extra extra bits of precision on input (To Be Confirmed)
1100 * @param hiPrec extra bits of precision on output (To Be Confirmed)
1101 * @return exp(x)
1102 */
1103 private static double exp(double x, double extra, double[] hiPrec) {
1104 double intPartA;
1105 double intPartB;
1106 int intVal = (int) x;
1107
1108 /* Lookup exp(floor(x)).
1109 * intPartA will have the upper 22 bits, intPartB will have the lower
1110 * 52 bits.
1111 */
1112 if (x < 0.0) {
1113
1114 // We don't check against intVal here as conversion of large negative double values
1115 // may be affected by a JIT bug. Subsequent comparisons can safely use intVal
1116 if (x < -746d) {
1117 if (hiPrec != null) {
1118 hiPrec[0] = 0.0;
1119 hiPrec[1] = 0.0;
1120 }
1121 return 0.0;
1122 }
1123
1124 if (intVal < -709) {
1125 /* This will produce a subnormal output */
1126 final double result = exp(x+40.19140625, extra, hiPrec) / 285040095144011776.0;
1127 if (hiPrec != null) {
1128 hiPrec[0] /= 285040095144011776.0;
1129 hiPrec[1] /= 285040095144011776.0;
1130 }
1131 return result;
1132 }
1133
1134 if (intVal == -709) {
1135 /* exp(1.494140625) is nearly a machine number... */
1136 final double result = exp(x+1.494140625, extra, hiPrec) / 4.455505956692756620;
1137 if (hiPrec != null) {
1138 hiPrec[0] /= 4.455505956692756620;
1139 hiPrec[1] /= 4.455505956692756620;
1140 }
1141 return result;
1142 }
1143
1144 intVal--;
1145
1146 } else {
1147 if (intVal > 709) {
1148 if (hiPrec != null) {
1149 hiPrec[0] = Double.POSITIVE_INFINITY;
1150 hiPrec[1] = 0.0;
1151 }
1152 return Double.POSITIVE_INFINITY;
1153 }
1154
1155 }
1156
1157 intPartA = ExpIntTable.EXP_INT_TABLE_A[EXP_INT_TABLE_MAX_INDEX+intVal];
1158 intPartB = ExpIntTable.EXP_INT_TABLE_B[EXP_INT_TABLE_MAX_INDEX+intVal];
1159
1160 /* Get the fractional part of x, find the greatest multiple of 2^-10 less than
1161 * x and look up the exp function of it.
1162 * fracPartA will have the upper 22 bits, fracPartB the lower 52 bits.
1163 */
1164 final int intFrac = (int) ((x - intVal) * 1024.0);
1165 final double fracPartA = ExpFracTable.EXP_FRAC_TABLE_A[intFrac];
1166 final double fracPartB = ExpFracTable.EXP_FRAC_TABLE_B[intFrac];
1167
1168 /* epsilon is the difference in x from the nearest multiple of 2^-10. It
1169 * has a value in the range 0 <= epsilon < 2^-10.
1170 * Do the subtraction from x as the last step to avoid possible loss of precision.
1171 */
1172 final double epsilon = x - (intVal + intFrac / 1024.0);
1173
1174 /* Compute z = exp(epsilon) - 1.0 via a minimax polynomial. z has
1175 full double precision (52 bits). Since z < 2^-10, we will have
1176 62 bits of precision when combined with the constant 1. This will be
1177 used in the last addition below to get proper rounding. */
1178
1179 /* Remez generated polynomial. Converges on the interval [0, 2^-10], error
1180 is less than 0.5 ULP */
1181 double z = 0.04168701738764507;
1182 z = z * epsilon + 0.1666666505023083;
1183 z = z * epsilon + 0.5000000000042687;
1184 z = z * epsilon + 1.0;
1185 z = z * epsilon + -3.940510424527919E-20;
1186
1187 /* Compute (intPartA+intPartB) * (fracPartA+fracPartB) by binomial
1188 expansion.
1189 tempA is exact since intPartA and intPartB only have 22 bits each.
1190 tempB will have 52 bits of precision.
1191 */
1192 double tempA = intPartA * fracPartA;
1193 double tempB = intPartA * fracPartB + intPartB * fracPartA + intPartB * fracPartB;
1194
1195 /* Compute the result. (1+z)(tempA+tempB). Order of operations is
1196 important. For accuracy add by increasing size. tempA is exact and
1197 much larger than the others. If there are extra bits specified from the
1198 pow() function, use them. */
1199 final double tempC = tempB + tempA;
1200
1201 // If tempC is positive infinite, the evaluation below could result in NaN,
1202 // because z could be negative at the same time.
1203 if (tempC == Double.POSITIVE_INFINITY) {
1204 if (hiPrec != null) {
1205 hiPrec[0] = Double.POSITIVE_INFINITY;
1206 hiPrec[1] = 0.0;
1207 }
1208 return Double.POSITIVE_INFINITY;
1209 }
1210
1211 final double result;
1212 if (extra != 0.0) {
1213 result = tempC*extra*z + tempC*extra + tempC*z + tempB + tempA;
1214 } else {
1215 result = tempC*z + tempB + tempA;
1216 }
1217
1218 if (hiPrec != null) {
1219 // If requesting high precision
1220 hiPrec[0] = tempA;
1221 hiPrec[1] = tempC*extra*z + tempC*extra + tempC*z + tempB;
1222 }
1223
1224 return result;
1225 }
1226
1227 /** Compute exp(x) - 1
1228 * @param x number to compute shifted exponential
1229 * @return exp(x) - 1
1230 */
1231 public static double expm1(double x) {
1232 return expm1(x, null);
1233 }
1234
1235 /** Internal helper method for expm1
1236 * @param x number to compute shifted exponential
1237 * @param hiPrecOut receive high precision result for -1.0 < x < 1.0
1238 * @return exp(x) - 1
1239 */
1240 private static double expm1(double x, double[] hiPrecOut) {
1241 if (Double.isNaN(x) || x == 0.0) { // NaN or zero
1242 return x;
1243 }
1244
1245 if (x <= -1.0 || x >= 1.0) {
1246 // If not between +/- 1.0
1247 //return exp(x) - 1.0;
1248 double[] hiPrec = new double[2];
1249 exp(x, 0.0, hiPrec);
1250 if (x > 0.0) {
1251 return -1.0 + hiPrec[0] + hiPrec[1];
1252 } else {
1253 final double ra = -1.0 + hiPrec[0];
1254 double rb = -(ra + 1.0 - hiPrec[0]);
1255 rb += hiPrec[1];
1256 return ra + rb;
1257 }
1258 }
1259
1260 double baseA;
1261 double baseB;
1262 double epsilon;
1263 boolean negative = false;
1264
1265 if (x < 0.0) {
1266 x = -x;
1267 negative = true;
1268 }
1269
1270 {
1271 int intFrac = (int) (x * 1024.0);
1272 double tempA = ExpFracTable.EXP_FRAC_TABLE_A[intFrac] - 1.0;
1273 double tempB = ExpFracTable.EXP_FRAC_TABLE_B[intFrac];
1274
1275 double temp = tempA + tempB;
1276 tempB = -(temp - tempA - tempB);
1277 tempA = temp;
1278
1279 temp = tempA * HEX_40000000;
1280 baseA = tempA + temp - temp;
1281 baseB = tempB + (tempA - baseA);
1282
1283 epsilon = x - intFrac/1024.0;
1284 }
1285
1286
1287 /* Compute expm1(epsilon) */
1288 double zb = 0.008336750013465571;
1289 zb = zb * epsilon + 0.041666663879186654;
1290 zb = zb * epsilon + 0.16666666666745392;
1291 zb = zb * epsilon + 0.49999999999999994;
1292 zb *= epsilon;
1293 zb *= epsilon;
1294
1295 double za = epsilon;
1296 double temp = za + zb;
1297 zb = -(temp - za - zb);
1298 za = temp;
1299
1300 temp = za * HEX_40000000;
1301 temp = za + temp - temp;
1302 zb += za - temp;
1303 za = temp;
1304
1305 /* Combine the parts. expm1(a+b) = expm1(a) + expm1(b) + expm1(a)*expm1(b) */
1306 double ya = za * baseA;
1307 //double yb = za*baseB + zb*baseA + zb*baseB;
1308 temp = ya + za * baseB;
1309 double yb = -(temp - ya - za * baseB);
1310 ya = temp;
1311
1312 temp = ya + zb * baseA;
1313 yb += -(temp - ya - zb * baseA);
1314 ya = temp;
1315
1316 temp = ya + zb * baseB;
1317 yb += -(temp - ya - zb*baseB);
1318 ya = temp;
1319
1320 //ya = ya + za + baseA;
1321 //yb = yb + zb + baseB;
1322 temp = ya + baseA;
1323 yb += -(temp - baseA - ya);
1324 ya = temp;
1325
1326 temp = ya + za;
1327 //yb += (ya > za) ? -(temp - ya - za) : -(temp - za - ya);
1328 yb += -(temp - ya - za);
1329 ya = temp;
1330
1331 temp = ya + baseB;
1332 //yb += (ya > baseB) ? -(temp - ya - baseB) : -(temp - baseB - ya);
1333 yb += -(temp - ya - baseB);
1334 ya = temp;
1335
1336 temp = ya + zb;
1337 //yb += (ya > zb) ? -(temp - ya - zb) : -(temp - zb - ya);
1338 yb += -(temp - ya - zb);
1339 ya = temp;
1340
1341 if (negative) {
1342 /* Compute expm1(-x) = -expm1(x) / (expm1(x) + 1) */
1343 double denom = 1.0 + ya;
1344 double denomr = 1.0 / denom;
1345 double denomb = -(denom - 1.0 - ya) + yb;
1346 double ratio = ya * denomr;
1347 temp = ratio * HEX_40000000;
1348 final double ra = ratio + temp - temp;
1349 double rb = ratio - ra;
1350
1351 temp = denom * HEX_40000000;
1352 za = denom + temp - temp;
1353 zb = denom - za;
1354
1355 rb += (ya - za * ra - za * rb - zb * ra - zb * rb) * denomr;
1356
1357 // f(x) = x/1+x
1358 // Compute f'(x)
1359 // Product rule: d(uv) = du*v + u*dv
1360 // Chain rule: d(f(g(x)) = f'(g(x))*f(g'(x))
1361 // d(1/x) = -1/(x*x)
1362 // d(1/1+x) = -1/( (1+x)^2) * 1 = -1/((1+x)*(1+x))
1363 // d(x/1+x) = -x/((1+x)(1+x)) + 1/1+x = 1 / ((1+x)(1+x))
1364
1365 // Adjust for yb
1366 rb += yb * denomr; // numerator
1367 rb += -ya * denomb * denomr * denomr; // denominator
1368
1369 // negate
1370 ya = -ra;
1371 yb = -rb;
1372 }
1373
1374 if (hiPrecOut != null) {
1375 hiPrecOut[0] = ya;
1376 hiPrecOut[1] = yb;
1377 }
1378
1379 return ya + yb;
1380 }
1381
1382 /**
1383 * Natural logarithm.
1384 *
1385 * @param x a double
1386 * @return log(x)
1387 */
1388 public static double log(final double x) {
1389 return log(x, null);
1390 }
1391
1392 /**
1393 * Internal helper method for natural logarithm function.
1394 * @param x original argument of the natural logarithm function
1395 * @param hiPrec extra bits of precision on output (To Be Confirmed)
1396 * @return log(x)
1397 */
1398 private static double log(final double x, final double[] hiPrec) {
1399 if (x==0) { // Handle special case of +0/-0
1400 return Double.NEGATIVE_INFINITY;
1401 }
1402 long bits = Double.doubleToRawLongBits(x);
1403
1404 /* Handle special cases of negative input, and NaN */
1405 if (((bits & 0x8000000000000000L) != 0 || Double.isNaN(x)) && x != 0.0) {
1406 if (hiPrec != null) {
1407 hiPrec[0] = Double.NaN;
1408 }
1409
1410 return Double.NaN;
1411 }
1412
1413 /* Handle special cases of Positive infinity. */
1414 if (x == Double.POSITIVE_INFINITY) {
1415 if (hiPrec != null) {
1416 hiPrec[0] = Double.POSITIVE_INFINITY;
1417 }
1418
1419 return Double.POSITIVE_INFINITY;
1420 }
1421
1422 /* Extract the exponent */
1423 int exp = (int)(bits >>> 52)-1023;
1424
1425 if ((bits & 0x7ff0000000000000L) == 0) {
1426 // Subnormal!
1427 if (x == 0) {
1428 // Zero
1429 if (hiPrec != null) {
1430 hiPrec[0] = Double.NEGATIVE_INFINITY;
1431 }
1432
1433 return Double.NEGATIVE_INFINITY;
1434 }
1435
1436 /* Normalize the subnormal number. */
1437 bits <<= 1;
1438 while ( (bits & 0x0010000000000000L) == 0) {
1439 --exp;
1440 bits <<= 1;
1441 }
1442 }
1443
1444
1445 if ((exp == -1 || exp == 0) && x < 1.01 && x > 0.99 && hiPrec == null) {
1446 /* The normal method doesn't work well in the range [0.99, 1.01], so call do a straight
1447 polynomial expansion in higer precision. */
1448
1449 /* Compute x - 1.0 and split it */
1450 double xa = x - 1.0;
1451 double tmp = xa * HEX_40000000;
1452 double aa = xa + tmp - tmp;
1453 double ab = xa - aa;
1454 xa = aa;
1455 double xb = ab;
1456
1457 final double[] lnCoef_last = LN_QUICK_COEF[LN_QUICK_COEF.length - 1];
1458 double ya = lnCoef_last[0];
1459 double yb = lnCoef_last[1];
1460
1461 for (int i = LN_QUICK_COEF.length - 2; i >= 0; i--) {
1462 /* Multiply a = y * x */
1463 aa = ya * xa;
1464 ab = ya * xb + yb * xa + yb * xb;
1465 /* split, so now y = a */
1466 tmp = aa * HEX_40000000;
1467 ya = aa + tmp - tmp;
1468 yb = aa - ya + ab;
1469
1470 /* Add a = y + lnQuickCoef */
1471 final double[] lnCoef_i = LN_QUICK_COEF[i];
1472 aa = ya + lnCoef_i[0];
1473 ab = yb + lnCoef_i[1];
1474 /* Split y = a */
1475 tmp = aa * HEX_40000000;
1476 ya = aa + tmp - tmp;
1477 yb = aa - ya + ab;
1478 }
1479
1480 /* Multiply a = y * x */
1481 aa = ya * xa;
1482 ab = ya * xb + yb * xa + yb * xb;
1483 /* split, so now y = a */
1484 tmp = aa * HEX_40000000;
1485 ya = aa + tmp - tmp;
1486 yb = aa - ya + ab;
1487
1488 return ya + yb;
1489 }
1490
1491 // lnm is a log of a number in the range of 1.0 - 2.0, so 0 <= lnm < ln(2)
1492 final double[] lnm = lnMant.LN_MANT[(int)((bits & 0x000ffc0000000000L) >> 42)];
1493
1494 /*
1495 double epsilon = x / Double.longBitsToDouble(bits & 0xfffffc0000000000L);
1496
1497 epsilon -= 1.0;
1498 */
1499
1500 // y is the most significant 10 bits of the mantissa
1501 //double y = Double.longBitsToDouble(bits & 0xfffffc0000000000L);
1502 //double epsilon = (x - y) / y;
1503 final double epsilon = (bits & 0x3ffffffffffL) / (TWO_POWER_52 + (bits & 0x000ffc0000000000L));
1504
1505 double lnza;
1506 double lnzb = 0.0;
1507
1508 if (hiPrec != null) {
1509 /* split epsilon -> x */
1510 double tmp = epsilon * HEX_40000000;
1511 double aa = epsilon + tmp - tmp;
1512 double ab = epsilon - aa;
1513 double xa = aa;
1514 double xb = ab;
1515
1516 /* Need a more accurate epsilon, so adjust the division. */
1517 final double numer = bits & 0x3ffffffffffL;
1518 final double denom = TWO_POWER_52 + (bits & 0x000ffc0000000000L);
1519 aa = numer - xa*denom - xb * denom;
1520 xb += aa / denom;
1521
1522 /* Remez polynomial evaluation */
1523 final double[] lnCoef_last = LN_HI_PREC_COEF[LN_HI_PREC_COEF.length-1];
1524 double ya = lnCoef_last[0];
1525 double yb = lnCoef_last[1];
1526
1527 for (int i = LN_HI_PREC_COEF.length - 2; i >= 0; i--) {
1528 /* Multiply a = y * x */
1529 aa = ya * xa;
1530 ab = ya * xb + yb * xa + yb * xb;
1531 /* split, so now y = a */
1532 tmp = aa * HEX_40000000;
1533 ya = aa + tmp - tmp;
1534 yb = aa - ya + ab;
1535
1536 /* Add a = y + lnHiPrecCoef */
1537 final double[] lnCoef_i = LN_HI_PREC_COEF[i];
1538 aa = ya + lnCoef_i[0];
1539 ab = yb + lnCoef_i[1];
1540 /* Split y = a */
1541 tmp = aa * HEX_40000000;
1542 ya = aa + tmp - tmp;
1543 yb = aa - ya + ab;
1544 }
1545
1546 /* Multiply a = y * x */
1547 aa = ya * xa;
1548 ab = ya * xb + yb * xa + yb * xb;
1549
1550 /* split, so now lnz = a */
1551 /*
1552 tmp = aa * 1073741824.0;
1553 lnza = aa + tmp - tmp;
1554 lnzb = aa - lnza + ab;
1555 */
1556 lnza = aa + ab;
1557 lnzb = -(lnza - aa - ab);
1558 } else {
1559 /* High precision not required. Eval Remez polynomial
1560 using standard double precision */
1561 lnza = -0.16624882440418567;
1562 lnza = lnza * epsilon + 0.19999954120254515;
1563 lnza = lnza * epsilon + -0.2499999997677497;
1564 lnza = lnza * epsilon + 0.3333333333332802;
1565 lnza = lnza * epsilon + -0.5;
1566 lnza = lnza * epsilon + 1.0;
1567 lnza *= epsilon;
1568 }
1569
1570 /* Relative sizes:
1571 * lnzb [0, 2.33E-10]
1572 * lnm[1] [0, 1.17E-7]
1573 * ln2B*exp [0, 1.12E-4]
1574 * lnza [0, 9.7E-4]
1575 * lnm[0] [0, 0.692]
1576 * ln2A*exp [0, 709]
1577 */
1578
1579 /* Compute the following sum:
1580 * lnzb + lnm[1] + ln2B*exp + lnza + lnm[0] + ln2A*exp;
1581 */
1582
1583 //return lnzb + lnm[1] + ln2B*exp + lnza + lnm[0] + ln2A*exp;
1584 double a = LN_2_A*exp;
1585 double b = 0.0;
1586 double c = a+lnm[0];
1587 double d = -(c-a-lnm[0]);
1588 a = c;
1589 b += d;
1590
1591 c = a + lnza;
1592 d = -(c - a - lnza);
1593 a = c;
1594 b += d;
1595
1596 c = a + LN_2_B*exp;
1597 d = -(c - a - LN_2_B*exp);
1598 a = c;
1599 b += d;
1600
1601 c = a + lnm[1];
1602 d = -(c - a - lnm[1]);
1603 a = c;
1604 b += d;
1605
1606 c = a + lnzb;
1607 d = -(c - a - lnzb);
1608 a = c;
1609 b += d;
1610
1611 if (hiPrec != null) {
1612 hiPrec[0] = a;
1613 hiPrec[1] = b;
1614 }
1615
1616 return a + b;
1617 }
1618
1619 /**
1620 * Computes log(1 + x).
1621 *
1622 * @param x Number.
1623 * @return {@code log(1 + x)}.
1624 */
1625 public static double log1p(final double x) {
1626 if (x == -1) {
1627 return Double.NEGATIVE_INFINITY;
1628 }
1629
1630 if (x == Double.POSITIVE_INFINITY) {
1631 return Double.POSITIVE_INFINITY;
1632 }
1633
1634 if (x > 1e-6 ||
1635 x < -1e-6) {
1636 final double xpa = 1 + x;
1637 final double xpb = -(xpa - 1 - x);
1638
1639 final double[] hiPrec = new double[2];
1640 final double lores = log(xpa, hiPrec);
1641 if (Double.isInfinite(lores)) { // Don't allow this to be converted to NaN
1642 return lores;
1643 }
1644
1645 // Do a taylor series expansion around xpa:
1646 // f(x+y) = f(x) + f'(x) y + f''(x)/2 y^2
1647 final double fx1 = xpb / xpa;
1648 final double epsilon = 0.5 * fx1 + 1;
1649 return epsilon * fx1 + hiPrec[1] + hiPrec[0];
1650 } else {
1651 // Value is small |x| < 1e6, do a Taylor series centered on 1.
1652 final double y = (x * F_1_3 - F_1_2) * x + 1;
1653 return y * x;
1654 }
1655 }
1656
1657 /** Compute the base 10 logarithm.
1658 * @param x a number
1659 * @return log10(x)
1660 */
1661 public static double log10(final double x) {
1662 final double[] hiPrec = new double[2];
1663
1664 final double lores = log(x, hiPrec);
1665 if (Double.isInfinite(lores)){ // don't allow this to be converted to NaN
1666 return lores;
1667 }
1668
1669 final double tmp = hiPrec[0] * HEX_40000000;
1670 final double lna = hiPrec[0] + tmp - tmp;
1671 final double lnb = hiPrec[0] - lna + hiPrec[1];
1672
1673 final double rln10a = 0.4342944622039795;
1674 final double rln10b = 1.9699272335463627E-8;
1675
1676 return rln10b * lnb + rln10b * lna + rln10a * lnb + rln10a * lna;
1677 }
1678
1679 /**
1680 * Computes the <a href="http://mathworld.wolfram.com/Logarithm.html">
1681 * logarithm</a> in a given base.
1682 *
1683 * Returns {@code NaN} if either argument is negative.
1684 * If {@code base} is 0 and {@code x} is positive, 0 is returned.
1685 * If {@code base} is positive and {@code x} is 0,
1686 * {@code Double.NEGATIVE_INFINITY} is returned.
1687 * If both arguments are 0, the result is {@code NaN}.
1688 *
1689 * @param base Base of the logarithm, must be greater than 0.
1690 * @param x Argument, must be greater than 0.
1691 * @return the value of the logarithm, i.e. the number {@code y} such that
1692 * <code>base<sup>y</sup> = x</code>.
1693 */
1694 public static double log(double base, double x) {
1695 return log(x) / log(base);
1696 }
1697
1698 /**
1699 * Power function. Compute x^y.
1700 *
1701 * @param x a double
1702 * @param y a double
1703 * @return double
1704 */
1705 public static double pow(final double x, final double y) {
1706
1707 if (y == 0) {
1708 // y = -0 or y = +0
1709 return 1.0;
1710 } else {
1711
1712 final long yBits = Double.doubleToRawLongBits(y);
1713 final int yRawExp = (int) ((yBits & MASK_DOUBLE_EXPONENT) >>> 52);
1714 final long yRawMantissa = yBits & MASK_DOUBLE_MANTISSA;
1715 final long xBits = Double.doubleToRawLongBits(x);
1716 final int xRawExp = (int) ((xBits & MASK_DOUBLE_EXPONENT) >>> 52);
1717 final long xRawMantissa = xBits & MASK_DOUBLE_MANTISSA;
1718
1719 if (yRawExp > 1085) {
1720 // y is either a very large integral value that does not fit in a long or it is a special number
1721
1722 if ((yRawExp == 2047 && yRawMantissa != 0) ||
1723 (xRawExp == 2047 && xRawMantissa != 0)) {
1724 // NaN
1725 return Double.NaN;
1726 } else if (xRawExp == 1023 && xRawMantissa == 0) {
1727 // x = -1.0 or x = +1.0
1728 if (yRawExp == 2047) {
1729 // y is infinite
1730 return Double.NaN;
1731 } else {
1732 // y is a large even integer
1733 return 1.0;
1734 }
1735 } else {
1736 // the absolute value of x is either greater or smaller than 1.0
1737
1738 // if yRawExp == 2047 and mantissa is 0, y = -infinity or y = +infinity
1739 // if 1085 < yRawExp < 2047, y is simply a large number, however, due to limited
1740 // accuracy, at this magnitude it behaves just like infinity with regards to x
1741 if ((y > 0) ^ (xRawExp < 1023)) {
1742 // either y = +infinity (or large engouh) and abs(x) > 1.0
1743 // or y = -infinity (or large engouh) and abs(x) < 1.0
1744 return Double.POSITIVE_INFINITY;
1745 } else {
1746 // either y = +infinity (or large engouh) and abs(x) < 1.0
1747 // or y = -infinity (or large engouh) and abs(x) > 1.0
1748 return +0.0;
1749 }
1750 }
1751
1752 } else {
1753 // y is a regular non-zero number
1754
1755 if (yRawExp >= 1023) {
1756 // y may be an integral value, which should be handled specifically
1757 final long yFullMantissa = IMPLICIT_HIGH_BIT | yRawMantissa;
1758 if (yRawExp < 1075) {
1759 // normal number with negative shift that may have a fractional part
1760 final long integralMask = (-1L) << (1075 - yRawExp);
1761 if ((yFullMantissa & integralMask) == yFullMantissa) {
1762 // all fractional bits are 0, the number is really integral
1763 final long l = yFullMantissa >> (1075 - yRawExp);
1764 return pow(x, (y < 0) ? -l : l);
1765 }
1766 } else {
1767 // normal number with positive shift, always an integral value
1768 // we know it fits in a primitive long because yRawExp > 1085 has been handled above
1769 final long l = yFullMantissa << (yRawExp - 1075);
1770 return pow(x, (y < 0) ? -l : l);
1771 }
1772 }
1773
1774 // y is a non-integral value
1775
1776 if (x == 0) {
1777 // x = -0 or x = +0
1778 // the integer powers have already been handled above
1779 return y < 0 ? Double.POSITIVE_INFINITY : +0.0;
1780 } else if (xRawExp == 2047) {
1781 if (xRawMantissa == 0) {
1782 // x = -infinity or x = +infinity
1783 return (y < 0) ? +0.0 : Double.POSITIVE_INFINITY;
1784 } else {
1785 // NaN
1786 return Double.NaN;
1787 }
1788 } else if (x < 0) {
1789 // the integer powers have already been handled above
1790 return Double.NaN;
1791 } else {
1792
1793 // this is the general case, for regular fractional numbers x and y
1794
1795 // Split y into ya and yb such that y = ya+yb
1796 final double tmp = y * HEX_40000000;
1797 final double ya = (y + tmp) - tmp;
1798 final double yb = y - ya;
1799
1800 /* Compute ln(x) */
1801 final double[] lns = new double[2];
1802 final double lores = log(x, lns);
1803 if (Double.isInfinite(lores)) { // don't allow this to be converted to NaN
1804 return lores;
1805 }
1806
1807 double lna = lns[0];
1808 double lnb = lns[1];
1809
1810 /* resplit lns */
1811 final double tmp1 = lna * HEX_40000000;
1812 final double tmp2 = (lna + tmp1) - tmp1;
1813 lnb += lna - tmp2;
1814 lna = tmp2;
1815
1816 // y*ln(x) = (aa+ab)
1817 final double aa = lna * ya;
1818 final double ab = lna * yb + lnb * ya + lnb * yb;
1819
1820 lna = aa+ab;
1821 lnb = -(lna - aa - ab);
1822
1823 double z = 1.0 / 120.0;
1824 z = z * lnb + (1.0 / 24.0);
1825 z = z * lnb + (1.0 / 6.0);
1826 z = z * lnb + 0.5;
1827 z = z * lnb + 1.0;
1828 z *= lnb;
1829
1830 return exp(lna, z, null);
1831
1832 }
1833 }
1834
1835 }
1836
1837 }
1838
1839 /**
1840 * Raise a double to an int power.
1841 *
1842 * @param d Number to raise.
1843 * @param e Exponent.
1844 * @return d<sup>e</sup>
1845 */
1846 public static double pow(double d, int e) {
1847 return pow(d, (long) e);
1848 }
1849
1850 /**
1851 * Raise a double to a long power.
1852 *
1853 * @param d Number to raise.
1854 * @param e Exponent.
1855 * @return d<sup>e</sup>
1856 */
1857 public static double pow(double d, long e) {
1858 if (e == 0) {
1859 return 1.0;
1860 } else if (e > 0) {
1861 return new Split(d).pow(e).full;
1862 } else {
1863 return new Split(d).reciprocal().pow(-e).full;
1864 }
1865 }
1866
1867 /** Class operator on double numbers split into one 26 bits number and one 27 bits number. */
1868 private static class Split {
1869
1870 /** Split version of NaN. */
1871 public static final Split NAN = new Split(Double.NaN, 0);
1872
1873 /** Split version of positive infinity. */
1874 public static final Split POSITIVE_INFINITY = new Split(Double.POSITIVE_INFINITY, 0);
1875
1876 /** Split version of negative infinity. */
1877 public static final Split NEGATIVE_INFINITY = new Split(Double.NEGATIVE_INFINITY, 0);
1878
1879 /** Full number. */
1880 private final double full;
1881
1882 /** High order bits. */
1883 private final double high;
1884
1885 /** Low order bits. */
1886 private final double low;
1887
1888 /** Simple constructor.
1889 * @param x number to split
1890 */
1891 Split(final double x) {
1892 full = x;
1893 high = Double.longBitsToDouble(Double.doubleToRawLongBits(x) & ((-1L) << 27));
1894 low = x - high;
1895 }
1896
1897 /** Simple constructor.
1898 * @param high high order bits
1899 * @param low low order bits
1900 */
1901 Split(final double high, final double low) {
1902 this(high == 0.0 ? (low == 0.0 && Double.doubleToRawLongBits(high) == Long.MIN_VALUE /* negative zero */ ? -0.0 : low) : high + low, high, low);
1903 }
1904
1905 /** Simple constructor.
1906 * @param full full number
1907 * @param high high order bits
1908 * @param low low order bits
1909 */
1910 Split(final double full, final double high, final double low) {
1911 this.full = full;
1912 this.high = high;
1913 this.low = low;
1914 }
1915
1916 /** Multiply the instance by another one.
1917 * @param b other instance to multiply by
1918 * @return product
1919 */
1920 public Split multiply(final Split b) {
1921 // beware the following expressions must NOT be simplified, they rely on floating point arithmetic properties
1922 final Split mulBasic = new Split(full * b.full);
1923 final double mulError = low * b.low - (((mulBasic.full - high * b.high) - low * b.high) - high * b.low);
1924 return new Split(mulBasic.high, mulBasic.low + mulError);
1925 }
1926
1927 /** Compute the reciprocal of the instance.
1928 * @return reciprocal of the instance
1929 */
1930 public Split reciprocal() {
1931
1932 final double approximateInv = 1.0 / full;
1933 final Split splitInv = new Split(approximateInv);
1934
1935 // if 1.0/d were computed perfectly, remultiplying it by d should give 1.0
1936 // we want to estimate the error so we can fix the low order bits of approximateInvLow
1937 // beware the following expressions must NOT be simplified, they rely on floating point arithmetic properties
1938 final Split product = multiply(splitInv);
1939 final double error = (product.high - 1) + product.low;
1940
1941 // better accuracy estimate of reciprocal
1942 return Double.isNaN(error) ? splitInv : new Split(splitInv.high, splitInv.low - error / full);
1943
1944 }
1945
1946 /** Computes this^e.
1947 * @param e exponent (beware, here it MUST be > 0; the only exclusion is Long.MIN_VALUE)
1948 * @return d^e, split in high and low bits
1949 */
1950 private Split pow(final long e) {
1951
1952 // prepare result
1953 Split result = new Split(1);
1954
1955 // d^(2p)
1956 Split d2p = new Split(full, high, low);
1957
1958 for (long p = e; p != 0; p >>>= 1) {
1959
1960 if ((p & 0x1) != 0) {
1961 // accurate multiplication result = result * d^(2p) using Veltkamp TwoProduct algorithm
1962 result = result.multiply(d2p);
1963 }
1964
1965 // accurate squaring d^(2(p+1)) = d^(2p) * d^(2p) using Veltkamp TwoProduct algorithm
1966 d2p = d2p.multiply(d2p);
1967
1968 }
1969
1970 if (Double.isNaN(result.full)) {
1971 if (Double.isNaN(full)) {
1972 return NAN;
1973 } else {
1974 // some intermediate numbers exceeded capacity,
1975 // and the low order bits became NaN (because infinity - infinity = NaN)
1976 if (abs(full) < 1) {
1977 return new Split(copySign(0.0, full), 0.0);
1978 } else if (full < 0 && (e & 0x1) == 1) {
1979 return NEGATIVE_INFINITY;
1980 } else {
1981 return POSITIVE_INFINITY;
1982 }
1983 }
1984 } else {
1985 return result;
1986 }
1987
1988 }
1989
1990 }
1991
1992 /**
1993 * Computes sin(x) - x, where |x| < 1/16.
1994 * Use a Remez polynomial approximation.
1995 * @param x a number smaller than 1/16
1996 * @return sin(x) - x
1997 */
1998 private static double polySine(final double x)
1999 {
2000 double x2 = x*x;
2001
2002 double p = 2.7553817452272217E-6;
2003 p = p * x2 + -1.9841269659586505E-4;
2004 p = p * x2 + 0.008333333333329196;
2005 p = p * x2 + -0.16666666666666666;
2006 //p *= x2;
2007 //p *= x;
2008 p = p * x2 * x;
2009
2010 return p;
2011 }
2012
2013 /**
2014 * Computes cos(x) - 1, where |x| < 1/16.
2015 * Use a Remez polynomial approximation.
2016 * @param x a number smaller than 1/16
2017 * @return cos(x) - 1
2018 */
2019 private static double polyCosine(double x) {
2020 double x2 = x*x;
2021
2022 double p = 2.479773539153719E-5;
2023 p = p * x2 + -0.0013888888689039883;
2024 p = p * x2 + 0.041666666666621166;
2025 p = p * x2 + -0.49999999999999994;
2026 p *= x2;
2027
2028 return p;
2029 }
2030
2031 /**
2032 * Compute sine over the first quadrant (0 < x < pi/2).
2033 * Use combination of table lookup and rational polynomial expansion.
2034 * @param xa number from which sine is requested
2035 * @param xb extra bits for x (may be 0.0)
2036 * @return sin(xa + xb)
2037 */
2038 private static double sinQ(double xa, double xb) {
2039 int idx = (int) ((xa * 8.0) + 0.5);
2040 final double epsilon = xa - EIGHTHS[idx]; //idx*0.125;
2041
2042 // Table lookups
2043 final double sintA = SINE_TABLE_A[idx];
2044 final double sintB = SINE_TABLE_B[idx];
2045 final double costA = COSINE_TABLE_A[idx];
2046 final double costB = COSINE_TABLE_B[idx];
2047
2048 // Polynomial eval of sin(epsilon), cos(epsilon)
2049 double sinEpsA = epsilon;
2050 double sinEpsB = polySine(epsilon);
2051 final double cosEpsA = 1.0;
2052 final double cosEpsB = polyCosine(epsilon);
2053
2054 // Split epsilon xa + xb = x
2055 final double temp = sinEpsA * HEX_40000000;
2056 double temp2 = (sinEpsA + temp) - temp;
2057 sinEpsB += sinEpsA - temp2;
2058 sinEpsA = temp2;
2059
2060 /* Compute sin(x) by angle addition formula */
2061 double result;
2062
2063 /* Compute the following sum:
2064 *
2065 * result = sintA + costA*sinEpsA + sintA*cosEpsB + costA*sinEpsB +
2066 * sintB + costB*sinEpsA + sintB*cosEpsB + costB*sinEpsB;
2067 *
2068 * Ranges of elements
2069 *
2070 * xxxtA 0 PI/2
2071 * xxxtB -1.5e-9 1.5e-9
2072 * sinEpsA -0.0625 0.0625
2073 * sinEpsB -6e-11 6e-11
2074 * cosEpsA 1.0
2075 * cosEpsB 0 -0.0625
2076 *
2077 */
2078
2079 //result = sintA + costA*sinEpsA + sintA*cosEpsB + costA*sinEpsB +
2080 // sintB + costB*sinEpsA + sintB*cosEpsB + costB*sinEpsB;
2081
2082 //result = sintA + sintA*cosEpsB + sintB + sintB * cosEpsB;
2083 //result += costA*sinEpsA + costA*sinEpsB + costB*sinEpsA + costB * sinEpsB;
2084 double a = 0;
2085 double b = 0;
2086
2087 double t = sintA;
2088 double c = a + t;
2089 double d = -(c - a - t);
2090 a = c;
2091 b += d;
2092
2093 t = costA * sinEpsA;
2094 c = a + t;
2095 d = -(c - a - t);
2096 a = c;
2097 b += d;
2098
2099 b = b + sintA * cosEpsB + costA * sinEpsB;
2100 /*
2101 t = sintA*cosEpsB;
2102 c = a + t;
2103 d = -(c - a - t);
2104 a = c;
2105 b = b + d;
2106
2107 t = costA*sinEpsB;
2108 c = a + t;
2109 d = -(c - a - t);
2110 a = c;
2111 b = b + d;
2112 */
2113
2114 b = b + sintB + costB * sinEpsA + sintB * cosEpsB + costB * sinEpsB;
2115 /*
2116 t = sintB;
2117 c = a + t;
2118 d = -(c - a - t);
2119 a = c;
2120 b = b + d;
2121
2122 t = costB*sinEpsA;
2123 c = a + t;
2124 d = -(c - a - t);
2125 a = c;
2126 b = b + d;
2127
2128 t = sintB*cosEpsB;
2129 c = a + t;
2130 d = -(c - a - t);
2131 a = c;
2132 b = b + d;
2133
2134 t = costB*sinEpsB;
2135 c = a + t;
2136 d = -(c - a - t);
2137 a = c;
2138 b = b + d;
2139 */
2140
2141 if (xb != 0.0) {
2142 t = ((costA + costB) * (cosEpsA + cosEpsB) -
2143 (sintA + sintB) * (sinEpsA + sinEpsB)) * xb; // approximate cosine*xb
2144 c = a + t;
2145 d = -(c - a - t);
2146 a = c;
2147 b += d;
2148 }
2149
2150 result = a + b;
2151
2152 return result;
2153 }
2154
2155 /**
2156 * Compute cosine in the first quadrant by subtracting input from PI/2 and
2157 * then calling sinQ. This is more accurate as the input approaches PI/2.
2158 * @param xa number from which cosine is requested
2159 * @param xb extra bits for x (may be 0.0)
2160 * @return cos(xa + xb)
2161 */
2162 private static double cosQ(double xa, double xb) {
2163 final double pi2a = 1.5707963267948966;
2164 final double pi2b = 6.123233995736766E-17;
2165
2166 final double a = pi2a - xa;
2167 double b = -(a - pi2a + xa);
2168 b += pi2b - xb;
2169
2170 return sinQ(a, b);
2171 }
2172
2173 /**
2174 * Compute tangent (or cotangent) over the first quadrant. 0 < x < pi/2
2175 * Use combination of table lookup and rational polynomial expansion.
2176 * @param xa number from which sine is requested
2177 * @param xb extra bits for x (may be 0.0)
2178 * @param cotanFlag if true, compute the cotangent instead of the tangent
2179 * @return tan(xa+xb) (or cotangent, depending on cotanFlag)
2180 */
2181 private static double tanQ(double xa, double xb, boolean cotanFlag) {
2182
2183 int idx = (int) ((xa * 8.0) + 0.5);
2184 final double epsilon = xa - EIGHTHS[idx]; //idx*0.125;
2185
2186 // Table lookups
2187 final double sintA = SINE_TABLE_A[idx];
2188 final double sintB = SINE_TABLE_B[idx];
2189 final double costA = COSINE_TABLE_A[idx];
2190 final double costB = COSINE_TABLE_B[idx];
2191
2192 // Polynomial eval of sin(epsilon), cos(epsilon)
2193 double sinEpsA = epsilon;
2194 double sinEpsB = polySine(epsilon);
2195 final double cosEpsA = 1.0;
2196 final double cosEpsB = polyCosine(epsilon);
2197
2198 // Split epsilon xa + xb = x
2199 double temp = sinEpsA * HEX_40000000;
2200 double temp2 = (sinEpsA + temp) - temp;
2201 sinEpsB += sinEpsA - temp2;
2202 sinEpsA = temp2;
2203
2204 /* Compute sin(x) by angle addition formula */
2205
2206 /* Compute the following sum:
2207 *
2208 * result = sintA + costA*sinEpsA + sintA*cosEpsB + costA*sinEpsB +
2209 * sintB + costB*sinEpsA + sintB*cosEpsB + costB*sinEpsB;
2210 *
2211 * Ranges of elements
2212 *
2213 * xxxtA 0 PI/2
2214 * xxxtB -1.5e-9 1.5e-9
2215 * sinEpsA -0.0625 0.0625
2216 * sinEpsB -6e-11 6e-11
2217 * cosEpsA 1.0
2218 * cosEpsB 0 -0.0625
2219 *
2220 */
2221
2222 //result = sintA + costA*sinEpsA + sintA*cosEpsB + costA*sinEpsB +
2223 // sintB + costB*sinEpsA + sintB*cosEpsB + costB*sinEpsB;
2224
2225 //result = sintA + sintA*cosEpsB + sintB + sintB * cosEpsB;
2226 //result += costA*sinEpsA + costA*sinEpsB + costB*sinEpsA + costB * sinEpsB;
2227 double a = 0;
2228 double b = 0;
2229
2230 // Compute sine
2231 double t = sintA;
2232 double c = a + t;
2233 double d = -(c - a - t);
2234 a = c;
2235 b += d;
2236
2237 t = costA*sinEpsA;
2238 c = a + t;
2239 d = -(c - a - t);
2240 a = c;
2241 b += d;
2242
2243 b += sintA*cosEpsB + costA*sinEpsB;
2244 b += sintB + costB*sinEpsA + sintB*cosEpsB + costB*sinEpsB;
2245
2246 double sina = a + b;
2247 double sinb = -(sina - a - b);
2248
2249 // Compute cosine
2250
2251 a = 0.0;
2252 b = 0.0;
2253
2254 t = costA*cosEpsA;
2255 c = a + t;
2256 d = -(c - a - t);
2257 a = c;
2258 b += d;
2259
2260 t = -sintA*sinEpsA;
2261 c = a + t;
2262 d = -(c - a - t);
2263 a = c;
2264 b += d;
2265
2266 b += costB*cosEpsA + costA*cosEpsB + costB*cosEpsB;
2267 b -= sintB*sinEpsA + sintA*sinEpsB + sintB*sinEpsB;
2268
2269 double cosa = a + b;
2270 double cosb = -(cosa - a - b);
2271
2272 if (cotanFlag) {
2273 double tmp;
2274 tmp = cosa; cosa = sina; sina = tmp;
2275 tmp = cosb; cosb = sinb; sinb = tmp;
2276 }
2277
2278
2279 /* estimate and correct, compute 1.0/(cosa+cosb) */
2280 /*
2281 double est = (sina+sinb)/(cosa+cosb);
2282 double err = (sina - cosa*est) + (sinb - cosb*est);
2283 est += err/(cosa+cosb);
2284 err = (sina - cosa*est) + (sinb - cosb*est);
2285 */
2286
2287 // f(x) = 1/x, f'(x) = -1/x^2
2288
2289 double est = sina/cosa;
2290
2291 /* Split the estimate to get more accurate read on division rounding */
2292 temp = est * HEX_40000000;
2293 double esta = (est + temp) - temp;
2294 double estb = est - esta;
2295
2296 temp = cosa * HEX_40000000;
2297 double cosaa = (cosa + temp) - temp;
2298 double cosab = cosa - cosaa;
2299
2300 //double err = (sina - est*cosa)/cosa; // Correction for division rounding
2301 double err = (sina - esta*cosaa - esta*cosab - estb*cosaa - estb*cosab)/cosa; // Correction for division rounding
2302 err += sinb/cosa; // Change in est due to sinb
2303 err += -sina * cosb / cosa / cosa; // Change in est due to cosb
2304
2305 if (xb != 0.0) {
2306 // tan' = 1 + tan^2 cot' = -(1 + cot^2)
2307 // Approximate impact of xb
2308 double xbadj = xb + est*est*xb;
2309 if (cotanFlag) {
2310 xbadj = -xbadj;
2311 }
2312
2313 err += xbadj;
2314 }
2315
2316 return est+err;
2317 }
2318
2319 /** Reduce the input argument using the Payne and Hanek method.
2320 * This is good for all inputs 0.0 < x < inf
2321 * Output is remainder after dividing by PI/2
2322 * The result array should contain 3 numbers.
2323 * result[0] is the integer portion, so mod 4 this gives the quadrant.
2324 * result[1] is the upper bits of the remainder
2325 * result[2] is the lower bits of the remainder
2326 *
2327 * @param x number to reduce
2328 * @param result placeholder where to put the result
2329 */
2330 private static void reducePayneHanek(double x, double[] result)
2331 {
2332 /* Convert input double to bits */
2333 long inbits = Double.doubleToRawLongBits(x);
2334 int exponent = (int) ((inbits >>> 52) & 0x7ff) - 1023;
2335
2336 /* Convert to fixed point representation */
2337 inbits &= 0x000fffffffffffffL;
2338 inbits |= 0x0010000000000000L;
2339
2340 /* Normalize input to be between 0.5 and 1.0 */
2341 exponent++;
2342 inbits <<= 11;
2343
2344 /* Based on the exponent, get a shifted copy of recip2pi */
2345 long shpi0;
2346 long shpiA;
2347 long shpiB;
2348 int idx = exponent >>> 6;
2349 int shift = exponent - (idx << 6);
2350
2351 if (shift != 0) {
2352 shpi0 = (idx == 0) ? 0 : (RECIP_2PI[idx-1] << shift);
2353 shpi0 |= RECIP_2PI[idx] >>> (64-shift);
2354 shpiA = (RECIP_2PI[idx] << shift) | (RECIP_2PI[idx+1] >>> (64-shift));
2355 shpiB = (RECIP_2PI[idx+1] << shift) | (RECIP_2PI[idx+2] >>> (64-shift));
2356 } else {
2357 shpi0 = (idx == 0) ? 0 : RECIP_2PI[idx-1];
2358 shpiA = RECIP_2PI[idx];
2359 shpiB = RECIP_2PI[idx+1];
2360 }
2361
2362 /* Multiply input by shpiA */
2363 long a = inbits >>> 32;
2364 long b = inbits & 0xffffffffL;
2365
2366 long c = shpiA >>> 32;
2367 long d = shpiA & 0xffffffffL;
2368
2369 long ac = a * c;
2370 long bd = b * d;
2371 long bc = b * c;
2372 long ad = a * d;
2373
2374 long prodB = bd + (ad << 32);
2375 long prodA = ac + (ad >>> 32);
2376
2377 boolean bita = (bd & 0x8000000000000000L) != 0;
2378 boolean bitb = (ad & 0x80000000L ) != 0;
2379 boolean bitsum = (prodB & 0x8000000000000000L) != 0;
2380
2381 /* Carry */
2382 if ( (bita && bitb) ||
2383 ((bita || bitb) && !bitsum) ) {
2384 prodA++;
2385 }
2386
2387 bita = (prodB & 0x8000000000000000L) != 0;
2388 bitb = (bc & 0x80000000L ) != 0;
2389
2390 prodB += bc << 32;
2391 prodA += bc >>> 32;
2392
2393 bitsum = (prodB & 0x8000000000000000L) != 0;
2394
2395 /* Carry */
2396 if ( (bita && bitb) ||
2397 ((bita || bitb) && !bitsum) ) {
2398 prodA++;
2399 }
2400
2401 /* Multiply input by shpiB */
2402 c = shpiB >>> 32;
2403 d = shpiB & 0xffffffffL;
2404 ac = a * c;
2405 bc = b * c;
2406 ad = a * d;
2407
2408 /* Collect terms */
2409 ac += (bc + ad) >>> 32;
2410
2411 bita = (prodB & 0x8000000000000000L) != 0;
2412 bitb = (ac & 0x8000000000000000L ) != 0;
2413 prodB += ac;
2414 bitsum = (prodB & 0x8000000000000000L) != 0;
2415 /* Carry */
2416 if ( (bita && bitb) ||
2417 ((bita || bitb) && !bitsum) ) {
2418 prodA++;
2419 }
2420
2421 /* Multiply by shpi0 */
2422 c = shpi0 >>> 32;
2423 d = shpi0 & 0xffffffffL;
2424
2425 bd = b * d;
2426 bc = b * c;
2427 ad = a * d;
2428
2429 prodA += bd + ((bc + ad) << 32);
2430
2431 /*
2432 * prodA, prodB now contain the remainder as a fraction of PI. We want this as a fraction of
2433 * PI/2, so use the following steps:
2434 * 1.) multiply by 4.
2435 * 2.) do a fixed point muliply by PI/4.
2436 * 3.) Convert to floating point.
2437 * 4.) Multiply by 2
2438 */
2439
2440 /* This identifies the quadrant */
2441 int intPart = (int)(prodA >>> 62);
2442
2443 /* Multiply by 4 */
2444 prodA <<= 2;
2445 prodA |= prodB >>> 62;
2446 prodB <<= 2;
2447
2448 /* Multiply by PI/4 */
2449 a = prodA >>> 32;
2450 b = prodA & 0xffffffffL;
2451
2452 c = PI_O_4_BITS[0] >>> 32;
2453 d = PI_O_4_BITS[0] & 0xffffffffL;
2454
2455 ac = a * c;
2456 bd = b * d;
2457 bc = b * c;
2458 ad = a * d;
2459
2460 long prod2B = bd + (ad << 32);
2461 long prod2A = ac + (ad >>> 32);
2462
2463 bita = (bd & 0x8000000000000000L) != 0;
2464 bitb = (ad & 0x80000000L ) != 0;
2465 bitsum = (prod2B & 0x8000000000000000L) != 0;
2466
2467 /* Carry */
2468 if ( (bita && bitb) ||
2469 ((bita || bitb) && !bitsum) ) {
2470 prod2A++;
2471 }
2472
2473 bita = (prod2B & 0x8000000000000000L) != 0;
2474 bitb = (bc & 0x80000000L ) != 0;
2475
2476 prod2B += bc << 32;
2477 prod2A += bc >>> 32;
2478
2479 bitsum = (prod2B & 0x8000000000000000L) != 0;
2480
2481 /* Carry */
2482 if ( (bita && bitb) ||
2483 ((bita || bitb) && !bitsum) ) {
2484 prod2A++;
2485 }
2486
2487 /* Multiply input by pio4bits[1] */
2488 c = PI_O_4_BITS[1] >>> 32;
2489 d = PI_O_4_BITS[1] & 0xffffffffL;
2490 ac = a * c;
2491 bc = b * c;
2492 ad = a * d;
2493
2494 /* Collect terms */
2495 ac += (bc + ad) >>> 32;
2496
2497 bita = (prod2B & 0x8000000000000000L) != 0;
2498 bitb = (ac & 0x8000000000000000L ) != 0;
2499 prod2B += ac;
2500 bitsum = (prod2B & 0x8000000000000000L) != 0;
2501 /* Carry */
2502 if ( (bita && bitb) ||
2503 ((bita || bitb) && !bitsum) ) {
2504 prod2A++;
2505 }
2506
2507 /* Multiply inputB by pio4bits[0] */
2508 a = prodB >>> 32;
2509 b = prodB & 0xffffffffL;
2510 c = PI_O_4_BITS[0] >>> 32;
2511 d = PI_O_4_BITS[0] & 0xffffffffL;
2512 ac = a * c;
2513 bc = b * c;
2514 ad = a * d;
2515
2516 /* Collect terms */
2517 ac += (bc + ad) >>> 32;
2518
2519 bita = (prod2B & 0x8000000000000000L) != 0;
2520 bitb = (ac & 0x8000000000000000L ) != 0;
2521 prod2B += ac;
2522 bitsum = (prod2B & 0x8000000000000000L) != 0;
2523 /* Carry */
2524 if ( (bita && bitb) ||
2525 ((bita || bitb) && !bitsum) ) {
2526 prod2A++;
2527 }
2528
2529 /* Convert to double */
2530 double tmpA = (prod2A >>> 12) / TWO_POWER_52; // High order 52 bits
2531 double tmpB = (((prod2A & 0xfffL) << 40) + (prod2B >>> 24)) / TWO_POWER_52 / TWO_POWER_52; // Low bits
2532
2533 double sumA = tmpA + tmpB;
2534 double sumB = -(sumA - tmpA - tmpB);
2535
2536 /* Multiply by PI/2 and return */
2537 result[0] = intPart;
2538 result[1] = sumA * 2.0;
2539 result[2] = sumB * 2.0;
2540 }
2541
2542 /**
2543 * Sine function.
2544 *
2545 * @param x Argument.
2546 * @return sin(x)
2547 */
2548 public static double sin(double x) {
2549 boolean negative = false;
2550 int quadrant = 0;
2551 double xa;
2552 double xb = 0.0;
2553
2554 /* Take absolute value of the input */
2555 xa = x;
2556 if (x < 0) {
2557 negative = true;
2558 xa = -xa;
2559 }
2560
2561 /* Check for zero and negative zero */
2562 if (xa == 0.0) {
2563 long bits = Double.doubleToRawLongBits(x);
2564 if (bits < 0) {
2565 return -0.0;
2566 }
2567 return 0.0;
2568 }
2569
2570 if (xa != xa || xa == Double.POSITIVE_INFINITY) {
2571 return Double.NaN;
2572 }
2573
2574 /* Perform any argument reduction */
2575 if (xa > 3294198.0) {
2576 // PI * (2**20)
2577 // Argument too big for CodyWaite reduction. Must use
2578 // PayneHanek.
2579 double[] reduceResults = new double[3];
2580 reducePayneHanek(xa, reduceResults);
2581 quadrant = ((int) reduceResults[0]) & 3;
2582 xa = reduceResults[1];
2583 xb = reduceResults[2];
2584 } else if (xa > 1.5707963267948966) {
2585 final CodyWaite cw = new CodyWaite(xa);
2586 quadrant = cw.getK() & 3;
2587 xa = cw.getRemA();
2588 xb = cw.getRemB();
2589 }
2590
2591 if (negative) {
2592 quadrant ^= 2; // Flip bit 1
2593 }
2594
2595 switch (quadrant) {
2596 case 0:
2597 return sinQ(xa, xb);
2598 case 1:
2599 return cosQ(xa, xb);
2600 case 2:
2601 return -sinQ(xa, xb);
2602 case 3:
2603 return -cosQ(xa, xb);
2604 default:
2605 return Double.NaN;
2606 }
2607 }
2608
2609 /**
2610 * Cosine function.
2611 *
2612 * @param x Argument.
2613 * @return cos(x)
2614 */
2615 public static double cos(double x) {
2616 int quadrant = 0;
2617
2618 /* Take absolute value of the input */
2619 double xa = x;
2620 if (x < 0) {
2621 xa = -xa;
2622 }
2623
2624 if (xa != xa || xa == Double.POSITIVE_INFINITY) {
2625 return Double.NaN;
2626 }
2627
2628 /* Perform any argument reduction */
2629 double xb = 0;
2630 if (xa > 3294198.0) {
2631 // PI * (2**20)
2632 // Argument too big for CodyWaite reduction. Must use
2633 // PayneHanek.
2634 double[] reduceResults = new double[3];
2635 reducePayneHanek(xa, reduceResults);
2636 quadrant = ((int) reduceResults[0]) & 3;
2637 xa = reduceResults[1];
2638 xb = reduceResults[2];
2639 } else if (xa > 1.5707963267948966) {
2640 final CodyWaite cw = new CodyWaite(xa);
2641 quadrant = cw.getK() & 3;
2642 xa = cw.getRemA();
2643 xb = cw.getRemB();
2644 }
2645
2646 //if (negative)
2647 // quadrant = (quadrant + 2) % 4;
2648
2649 switch (quadrant) {
2650 case 0:
2651 return cosQ(xa, xb);
2652 case 1:
2653 return -sinQ(xa, xb);
2654 case 2:
2655 return -cosQ(xa, xb);
2656 case 3:
2657 return sinQ(xa, xb);
2658 default:
2659 return Double.NaN;
2660 }
2661 }
2662
2663 /**
2664 * Combined Sine and Cosine function.
2665 *
2666 * @param x Argument.
2667 * @return [sin(x), cos(x)]
2668 */
2669 public static SinCos sinCos(double x) {
2670 boolean negative = false;
2671 int quadrant = 0;
2672 double xa;
2673 double xb = 0.0;
2674
2675 /* Take absolute value of the input */
2676 xa = x;
2677 if (x < 0) {
2678 negative = true;
2679 xa = -xa;
2680 }
2681
2682 /* Check for zero and negative zero */
2683 if (xa == 0.0) {
2684 long bits = Double.doubleToRawLongBits(x);
2685 if (bits < 0) {
2686 return new SinCos(-0.0, 1.0);
2687 }
2688 return new SinCos(0.0, 1.0);
2689 }
2690
2691 if (xa != xa || xa == Double.POSITIVE_INFINITY) {
2692 return new SinCos(Double.NaN, Double.NaN);
2693 }
2694
2695 /* Perform any argument reduction */
2696 if (xa > 3294198.0) {
2697 // PI * (2**20)
2698 // Argument too big for CodyWaite reduction. Must use
2699 // PayneHanek.
2700 double[] reduceResults = new double[3];
2701 reducePayneHanek(xa, reduceResults);
2702 quadrant = ((int) reduceResults[0]) & 3;
2703 xa = reduceResults[1];
2704 xb = reduceResults[2];
2705 } else if (xa > 1.5707963267948966) {
2706 final CodyWaite cw = new CodyWaite(xa);
2707 quadrant = cw.getK() & 3;
2708 xa = cw.getRemA();
2709 xb = cw.getRemB();
2710 }
2711
2712 switch (quadrant) {
2713 case 0:
2714 return new SinCos(negative ? -sinQ(xa, xb) : sinQ(xa, xb), cosQ(xa, xb));
2715 case 1:
2716 return new SinCos(negative ? -cosQ(xa, xb) : cosQ(xa, xb), -sinQ(xa, xb));
2717 case 2:
2718 return new SinCos(negative ? sinQ(xa, xb) : -sinQ(xa, xb), -cosQ(xa, xb));
2719 case 3:
2720 return new SinCos(negative ? cosQ(xa, xb) : -cosQ(xa, xb), sinQ(xa, xb));
2721 default:
2722 return new SinCos(Double.NaN, Double.NaN);
2723 }
2724 }
2725
2726 /**
2727 * Combined Sine and Cosine function.
2728 *
2729 * @param x Argument.
2730 * @param <T> the type of the field element
2731 * @return [sin(x), cos(x)]
2732 * @since 1.4
2733 */
2734 public static <T extends CalculusFieldElement<T>> FieldSinCos<T> sinCos(T x) {
2735 return x.sinCos();
2736 }
2737
2738 /**
2739 * Tangent function.
2740 *
2741 * @param x Argument.
2742 * @return tan(x)
2743 */
2744 public static double tan(double x) {
2745 boolean negative = false;
2746 int quadrant = 0;
2747
2748 /* Take absolute value of the input */
2749 double xa = x;
2750 if (x < 0) {
2751 negative = true;
2752 xa = -xa;
2753 }
2754
2755 /* Check for zero and negative zero */
2756 if (xa == 0.0) {
2757 long bits = Double.doubleToRawLongBits(x);
2758 if (bits < 0) {
2759 return -0.0;
2760 }
2761 return 0.0;
2762 }
2763
2764 if (xa != xa || xa == Double.POSITIVE_INFINITY) {
2765 return Double.NaN;
2766 }
2767
2768 /* Perform any argument reduction */
2769 double xb = 0;
2770 if (xa > 3294198.0) {
2771 // PI * (2**20)
2772 // Argument too big for CodyWaite reduction. Must use
2773 // PayneHanek.
2774 double[] reduceResults = new double[3];
2775 reducePayneHanek(xa, reduceResults);
2776 quadrant = ((int) reduceResults[0]) & 3;
2777 xa = reduceResults[1];
2778 xb = reduceResults[2];
2779 } else if (xa > 1.5707963267948966) {
2780 final CodyWaite cw = new CodyWaite(xa);
2781 quadrant = cw.getK() & 3;
2782 xa = cw.getRemA();
2783 xb = cw.getRemB();
2784 }
2785
2786 if (xa > 1.5) {
2787 // Accuracy suffers between 1.5 and PI/2
2788 final double pi2a = 1.5707963267948966;
2789 final double pi2b = 6.123233995736766E-17;
2790
2791 final double a = pi2a - xa;
2792 double b = -(a - pi2a + xa);
2793 b += pi2b - xb;
2794
2795 xa = a + b;
2796 xb = -(xa - a - b);
2797 quadrant ^= 1;
2798 negative ^= true;
2799 }
2800
2801 double result;
2802 if ((quadrant & 1) == 0) {
2803 result = tanQ(xa, xb, false);
2804 } else {
2805 result = -tanQ(xa, xb, true);
2806 }
2807
2808 if (negative) {
2809 result = -result;
2810 }
2811
2812 return result;
2813 }
2814
2815 /**
2816 * Arctangent function
2817 * @param x a number
2818 * @return atan(x)
2819 */
2820 public static double atan(double x) {
2821 return atan(x, 0.0, false);
2822 }
2823
2824 /** Internal helper function to compute arctangent.
2825 * @param xa number from which arctangent is requested
2826 * @param xb extra bits for x (may be 0.0)
2827 * @param leftPlane if true, result angle must be put in the left half plane
2828 * @return atan(xa + xb) (or angle shifted by {@code PI} if leftPlane is true)
2829 */
2830 private static double atan(double xa, double xb, boolean leftPlane) {
2831 if (xa == 0.0) { // Matches +/- 0.0; return correct sign
2832 return leftPlane ? copySign(Math.PI, xa) : xa;
2833 }
2834
2835 final boolean negate;
2836 if (xa < 0) {
2837 // negative
2838 xa = -xa;
2839 xb = -xb;
2840 negate = true;
2841 } else {
2842 negate = false;
2843 }
2844
2845 if (xa > 1.633123935319537E16) { // Very large input
2846 return (negate ^ leftPlane) ? (-Math.PI * F_1_2) : (Math.PI * F_1_2);
2847 }
2848
2849 /* Estimate the closest tabulated arctan value, compute eps = xa-tangentTable */
2850 final int idx;
2851 if (xa < 1) {
2852 idx = (int) (((-1.7168146928204136 * xa * xa + 8.0) * xa) + 0.5);
2853 } else {
2854 final double oneOverXa = 1 / xa;
2855 idx = (int) (-((-1.7168146928204136 * oneOverXa * oneOverXa + 8.0) * oneOverXa) + 13.07);
2856 }
2857
2858 final double ttA = TANGENT_TABLE_A[idx];
2859 final double ttB = TANGENT_TABLE_B[idx];
2860
2861 double epsA = xa - ttA;
2862 double epsB = -(epsA - xa + ttA);
2863 epsB += xb - ttB;
2864
2865 double temp = epsA + epsB;
2866 epsB = -(temp - epsA - epsB);
2867 epsA = temp;
2868
2869 /* Compute eps = eps / (1.0 + xa*tangent) */
2870 temp = xa * HEX_40000000;
2871 double ya = xa + temp - temp;
2872 double yb = xb + xa - ya;
2873 xa = ya;
2874 xb += yb;
2875
2876 //if (idx > 8 || idx == 0)
2877 if (idx == 0) {
2878 /* If the slope of the arctan is gentle enough (< 0.45), this approximation will suffice */
2879 //double denom = 1.0 / (1.0 + xa*tangentTableA[idx] + xb*tangentTableA[idx] + xa*tangentTableB[idx] + xb*tangentTableB[idx]);
2880 final double denom = 1d / (1d + (xa + xb) * (ttA + ttB));
2881 //double denom = 1.0 / (1.0 + xa*tangentTableA[idx]);
2882 ya = epsA * denom;
2883 yb = epsB * denom;
2884 } else {
2885 double temp2 = xa * ttA;
2886 double za = 1d + temp2;
2887 double zb = -(za - 1d - temp2);
2888 temp2 = xb * ttA + xa * ttB;
2889 temp = za + temp2;
2890 zb += -(temp - za - temp2);
2891 za = temp;
2892
2893 zb += xb * ttB;
2894 ya = epsA / za;
2895
2896 temp = ya * HEX_40000000;
2897 final double yaa = (ya + temp) - temp;
2898 final double yab = ya - yaa;
2899
2900 temp = za * HEX_40000000;
2901 final double zaa = (za + temp) - temp;
2902 final double zab = za - zaa;
2903
2904 /* Correct for rounding in division */
2905 yb = (epsA - yaa * zaa - yaa * zab - yab * zaa - yab * zab) / za;
2906
2907 yb += -epsA * zb / za / za;
2908 yb += epsB / za;
2909 }
2910
2911
2912 epsA = ya;
2913 epsB = yb;
2914
2915 /* Evaluate polynomial */
2916 final double epsA2 = epsA * epsA;
2917
2918 /*
2919 yb = -0.09001346640161823;
2920 yb = yb * epsA2 + 0.11110718400605211;
2921 yb = yb * epsA2 + -0.1428571349122913;
2922 yb = yb * epsA2 + 0.19999999999273194;
2923 yb = yb * epsA2 + -0.33333333333333093;
2924 yb = yb * epsA2 * epsA;
2925 */
2926
2927 yb = 0.07490822288864472;
2928 yb = yb * epsA2 - 0.09088450866185192;
2929 yb = yb * epsA2 + 0.11111095942313305;
2930 yb = yb * epsA2 - 0.1428571423679182;
2931 yb = yb * epsA2 + 0.19999999999923582;
2932 yb = yb * epsA2 - 0.33333333333333287;
2933 yb = yb * epsA2 * epsA;
2934
2935
2936 ya = epsA;
2937
2938 temp = ya + yb;
2939 yb = -(temp - ya - yb);
2940 ya = temp;
2941
2942 /* Add in effect of epsB. atan'(x) = 1/(1+x^2) */
2943 yb += epsB / (1d + epsA * epsA);
2944
2945 final double eighths = EIGHTHS[idx];
2946
2947 //result = yb + eighths[idx] + ya;
2948 double za = eighths + ya;
2949 double zb = -(za - eighths - ya);
2950 temp = za + yb;
2951 zb += -(temp - za - yb);
2952 za = temp;
2953
2954 double result = za + zb;
2955
2956 if (leftPlane) {
2957 // Result is in the left plane
2958 final double resultb = -(result - za - zb);
2959 final double pia = 1.5707963267948966 * 2;
2960 final double pib = 6.123233995736766E-17 * 2;
2961
2962 za = pia - result;
2963 zb = -(za - pia + result);
2964 zb += pib - resultb;
2965
2966 result = za + zb;
2967 }
2968
2969
2970 if (negate ^ leftPlane) {
2971 result = -result;
2972 }
2973
2974 return result;
2975 }
2976
2977 /**
2978 * Two arguments arctangent function
2979 * @param y ordinate
2980 * @param x abscissa
2981 * @return phase angle of point (x,y) between {@code -PI} and {@code PI}
2982 */
2983 public static double atan2(double y, double x) {
2984 if (Double.isNaN(x) || Double.isNaN(y)) {
2985 return Double.NaN;
2986 }
2987
2988 if (y == 0) {
2989 final double result = x * y;
2990 final double invx = 1d / x;
2991
2992 if (invx == 0) { // X is infinite
2993 if (x > 0) {
2994 return y; // return +/- 0.0
2995 } else {
2996 return copySign(Math.PI, y);
2997 }
2998 }
2999
3000 if (x < 0 || invx < 0) {
3001 return copySign(Math.PI, y);
3002 } else {
3003 return result;
3004 }
3005 }
3006
3007 // y cannot now be zero
3008
3009 if (y == Double.POSITIVE_INFINITY) {
3010 if (x == Double.POSITIVE_INFINITY) {
3011 return Math.PI * F_1_4;
3012 }
3013
3014 if (x == Double.NEGATIVE_INFINITY) {
3015 return Math.PI * F_3_4;
3016 }
3017
3018 return Math.PI * F_1_2;
3019 }
3020
3021 if (y == Double.NEGATIVE_INFINITY) {
3022 if (x == Double.POSITIVE_INFINITY) {
3023 return -Math.PI * F_1_4;
3024 }
3025
3026 if (x == Double.NEGATIVE_INFINITY) {
3027 return -Math.PI * F_3_4;
3028 }
3029
3030 return -Math.PI * F_1_2;
3031 }
3032
3033 if (x == Double.POSITIVE_INFINITY) {
3034 return copySign(0d, y);
3035 }
3036
3037 if (x == Double.NEGATIVE_INFINITY)
3038 {
3039 return copySign(Math.PI, y);
3040 }
3041
3042 // Neither y nor x can be infinite or NAN here
3043
3044 if (x == 0) {
3045 return copySign(Math.PI * F_1_2, y);
3046 }
3047
3048 // Compute ratio r = y/x
3049 final double r = y / x;
3050 if (Double.isInfinite(r)) { // bypass calculations that can create NaN
3051 return atan(r, 0, x < 0);
3052 }
3053
3054 double ra = doubleHighPart(r);
3055 double rb = r - ra;
3056
3057 // Split x
3058 final double xa = doubleHighPart(x);
3059 final double xb = x - xa;
3060
3061 rb += (y - ra * xa - ra * xb - rb * xa - rb * xb) / x;
3062
3063 final double temp = ra + rb;
3064 rb = -(temp - ra - rb);
3065 ra = temp;
3066
3067 if (ra == 0) { // Fix up the sign so atan works correctly
3068 ra = copySign(0d, y);
3069 }
3070
3071 // Call atan
3072 return atan(ra, rb, x < 0);
3073
3074 }
3075
3076 /** Compute the arc sine of a number.
3077 * @param x number on which evaluation is done
3078 * @return arc sine of x
3079 */
3080 public static double asin(double x) {
3081 if (Double.isNaN(x)) {
3082 return Double.NaN;
3083 }
3084
3085 if (x > 1.0 || x < -1.0) {
3086 return Double.NaN;
3087 }
3088
3089 if (x == 1.0) {
3090 return Math.PI/2.0;
3091 }
3092
3093 if (x == -1.0) {
3094 return -Math.PI/2.0;
3095 }
3096
3097 if (x == 0.0) { // Matches +/- 0.0; return correct sign
3098 return x;
3099 }
3100
3101 /* Compute asin(x) = atan(x/sqrt(1-x*x)) */
3102
3103 /* Split x */
3104 double temp = x * HEX_40000000;
3105 final double xa = x + temp - temp;
3106 final double xb = x - xa;
3107
3108 /* Square it */
3109 double ya = xa*xa;
3110 double yb = xa*xb*2.0 + xb*xb;
3111
3112 /* Subtract from 1 */
3113 ya = -ya;
3114 yb = -yb;
3115
3116 double za = 1.0 + ya;
3117 double zb = -(za - 1.0 - ya);
3118
3119 temp = za + yb;
3120 zb += -(temp - za - yb);
3121 za = temp;
3122
3123 /* Square root */
3124 double y;
3125 y = sqrt(za);
3126 temp = y * HEX_40000000;
3127 ya = y + temp - temp;
3128 yb = y - ya;
3129
3130 /* Extend precision of sqrt */
3131 yb += (za - ya*ya - 2*ya*yb - yb*yb) / (2.0*y);
3132
3133 /* Contribution of zb to sqrt */
3134 double dx = zb / (2.0*y);
3135
3136 // Compute ratio r = x/y
3137 double r = x/y;
3138 temp = r * HEX_40000000;
3139 double ra = r + temp - temp;
3140 double rb = r - ra;
3141
3142 rb += (x - ra*ya - ra*yb - rb*ya - rb*yb) / y; // Correct for rounding in division
3143 rb += -x * dx / y / y; // Add in effect additional bits of sqrt.
3144
3145 temp = ra + rb;
3146 rb = -(temp - ra - rb);
3147 ra = temp;
3148
3149 return atan(ra, rb, false);
3150 }
3151
3152 /** Compute the arc cosine of a number.
3153 * @param x number on which evaluation is done
3154 * @return arc cosine of x
3155 */
3156 public static double acos(double x) {
3157 if (Double.isNaN(x)) {
3158 return Double.NaN;
3159 }
3160
3161 if (x > 1.0 || x < -1.0) {
3162 return Double.NaN;
3163 }
3164
3165 if (x == -1.0) {
3166 return Math.PI;
3167 }
3168
3169 if (x == 1.0) {
3170 return 0.0;
3171 }
3172
3173 if (x == 0) {
3174 return Math.PI/2.0;
3175 }
3176
3177 /* Compute acos(x) = atan(sqrt(1-x*x)/x) */
3178
3179 /* Split x */
3180 double temp = x * HEX_40000000;
3181 final double xa = x + temp - temp;
3182 final double xb = x - xa;
3183
3184 /* Square it */
3185 double ya = xa*xa;
3186 double yb = xa*xb*2.0 + xb*xb;
3187
3188 /* Subtract from 1 */
3189 ya = -ya;
3190 yb = -yb;
3191
3192 double za = 1.0 + ya;
3193 double zb = -(za - 1.0 - ya);
3194
3195 temp = za + yb;
3196 zb += -(temp - za - yb);
3197 za = temp;
3198
3199 /* Square root */
3200 double y = sqrt(za);
3201 temp = y * HEX_40000000;
3202 ya = y + temp - temp;
3203 yb = y - ya;
3204
3205 /* Extend precision of sqrt */
3206 yb += (za - ya*ya - 2*ya*yb - yb*yb) / (2.0*y);
3207
3208 /* Contribution of zb to sqrt */
3209 yb += zb / (2.0*y);
3210 y = ya+yb;
3211 yb = -(y - ya - yb);
3212
3213 // Compute ratio r = y/x
3214 double r = y/x;
3215
3216 // Did r overflow?
3217 if (Double.isInfinite(r)) { // x is effectively zero
3218 return Math.PI/2; // so return the appropriate value
3219 }
3220
3221 double ra = doubleHighPart(r);
3222 double rb = r - ra;
3223
3224 rb += (y - ra*xa - ra*xb - rb*xa - rb*xb) / x; // Correct for rounding in division
3225 rb += yb / x; // Add in effect additional bits of sqrt.
3226
3227 temp = ra + rb;
3228 rb = -(temp - ra - rb);
3229 ra = temp;
3230
3231 return atan(ra, rb, x<0);
3232 }
3233
3234 /** Compute the cubic root of a number.
3235 * @param x number on which evaluation is done
3236 * @return cubic root of x
3237 */
3238 public static double cbrt(double x) {
3239 /* Convert input double to bits */
3240 long inbits = Double.doubleToRawLongBits(x);
3241 int exponent = (int) ((inbits >>> 52) & 0x7ff) - 1023;
3242 boolean subnormal = false;
3243
3244 if (exponent == -1023) {
3245 if (x == 0) {
3246 return x;
3247 }
3248
3249 /* Subnormal, so normalize */
3250 subnormal = true;
3251 x *= 1.8014398509481984E16; // 2^54
3252 inbits = Double.doubleToRawLongBits(x);
3253 exponent = (int) ((inbits >>> 52) & 0x7ff) - 1023;
3254 }
3255
3256 if (exponent == 1024) {
3257 // Nan or infinity. Don't care which.
3258 return x;
3259 }
3260
3261 /* Divide the exponent by 3 */
3262 int exp3 = exponent / 3;
3263
3264 /* p2 will be the nearest power of 2 to x with its exponent divided by 3 */
3265 double p2 = Double.longBitsToDouble((inbits & 0x8000000000000000L) |
3266 (long)(((exp3 + 1023) & 0x7ff)) << 52);
3267
3268 /* This will be a number between 1 and 2 */
3269 final double mant = Double.longBitsToDouble((inbits & 0x000fffffffffffffL) | 0x3ff0000000000000L);
3270
3271 /* Estimate the cube root of mant by polynomial */
3272 double est = -0.010714690733195933;
3273 est = est * mant + 0.0875862700108075;
3274 est = est * mant + -0.3058015757857271;
3275 est = est * mant + 0.7249995199969751;
3276 est = est * mant + 0.5039018405998233;
3277
3278 est *= CBRTTWO[exponent % 3 + 2];
3279
3280 // est should now be good to about 15 bits of precision. Do 2 rounds of
3281 // Newton's method to get closer, this should get us full double precision
3282 // Scale down x for the purpose of doing newtons method. This avoids over/under flows.
3283 final double xs = x / (p2*p2*p2);
3284 est += (xs - est*est*est) / (3*est*est);
3285 est += (xs - est*est*est) / (3*est*est);
3286
3287 // Do one round of Newton's method in extended precision to get the last bit right.
3288 double temp = est * HEX_40000000;
3289 double ya = est + temp - temp;
3290 double yb = est - ya;
3291
3292 double za = ya * ya;
3293 double zb = ya * yb * 2.0 + yb * yb;
3294 temp = za * HEX_40000000;
3295 double temp2 = za + temp - temp;
3296 zb += za - temp2;
3297 za = temp2;
3298
3299 zb = za * yb + ya * zb + zb * yb;
3300 za *= ya;
3301
3302 double na = xs - za;
3303 double nb = -(na - xs + za);
3304 nb -= zb;
3305
3306 est += (na+nb)/(3*est*est);
3307
3308 /* Scale by a power of two, so this is exact. */
3309 est *= p2;
3310
3311 if (subnormal) {
3312 est *= 3.814697265625E-6; // 2^-18
3313 }
3314
3315 return est;
3316 }
3317
3318 /**
3319 * Convert degrees to radians, with error of less than 0.5 ULP
3320 * @param x angle in degrees
3321 * @return x converted into radians
3322 */
3323 public static double toRadians(double x)
3324 {
3325 if (Double.isInfinite(x) || x == 0.0) { // Matches +/- 0.0; return correct sign
3326 return x;
3327 }
3328
3329 // These are PI/180 split into high and low order bits
3330 final double facta = 0.01745329052209854;
3331 final double factb = 1.997844754509471E-9;
3332
3333 double xa = doubleHighPart(x);
3334 double xb = x - xa;
3335
3336 double result = xb * factb + xb * facta + xa * factb + xa * facta;
3337 if (result == 0) {
3338 result *= x; // ensure correct sign if calculation underflows
3339 }
3340 return result;
3341 }
3342
3343 /**
3344 * Convert radians to degrees, with error of less than 0.5 ULP
3345 * @param x angle in radians
3346 * @return x converted into degrees
3347 */
3348 public static double toDegrees(double x)
3349 {
3350 if (Double.isInfinite(x) || x == 0.0) { // Matches +/- 0.0; return correct sign
3351 return x;
3352 }
3353
3354 // These are 180/PI split into high and low order bits
3355 final double facta = 57.2957763671875;
3356 final double factb = 3.145894820876798E-6;
3357
3358 double xa = doubleHighPart(x);
3359 double xb = x - xa;
3360
3361 return xb * factb + xb * facta + xa * factb + xa * facta;
3362 }
3363
3364 /**
3365 * Absolute value.
3366 * @param x number from which absolute value is requested
3367 * @return abs(x)
3368 */
3369 public static int abs(final int x) {
3370 final int i = x >>> 31;
3371 return (x ^ (~i + 1)) + i;
3372 }
3373
3374 /**
3375 * Absolute value.
3376 * @param x number from which absolute value is requested
3377 * @return abs(x)
3378 */
3379 public static long abs(final long x) {
3380 final long l = x >>> 63;
3381 // l is one if x negative zero else
3382 // ~l+1 is zero if x is positive, -1 if x is negative
3383 // x^(~l+1) is x is x is positive, ~x if x is negative
3384 // add around
3385 return (x ^ (~l + 1)) + l;
3386 }
3387
3388 /**
3389 * Absolute value.
3390 * @param x number from which absolute value is requested
3391 * @return abs(x), or throws an exception for {@code Integer.MIN_VALUE}
3392 * @since 2.0
3393 */
3394 public static int absExact(final int x) {
3395 if (x == Integer.MIN_VALUE) {
3396 throw new ArithmeticException();
3397 }
3398 return abs(x);
3399 }
3400
3401 /**
3402 * Absolute value.
3403 * @param x number from which absolute value is requested
3404 * @return abs(x), or throws an exception for {@code Long.MIN_VALUE}
3405 * @since 2.0
3406 */
3407 public static long absExact(final long x) {
3408 if (x == Long.MIN_VALUE) {
3409 throw new ArithmeticException();
3410 }
3411 return abs(x);
3412 }
3413
3414 /**
3415 * Absolute value.
3416 * @param x number from which absolute value is requested
3417 * @return abs(x)
3418 * @since 2.0
3419 */
3420 public static float abs(final float x) {
3421 return Float.intBitsToFloat(MASK_NON_SIGN_INT & Float.floatToRawIntBits(x));
3422 }
3423
3424 /**
3425 * Absolute value.
3426 * @param x number from which absolute value is requested
3427 * @return abs(x)
3428 */
3429 public static double abs(double x) {
3430 return Double.longBitsToDouble(MASK_NON_SIGN_LONG & Double.doubleToRawLongBits(x));
3431 }
3432
3433 /**
3434 * Negates the argument.
3435 * @param x number from which opposite value is requested
3436 * @return -x, or throws an exception for {@code Integer.MIN_VALUE}
3437 * @since 2.0
3438 */
3439 public static int negateExact(final int x) {
3440 if (x == Integer.MIN_VALUE) {
3441 throw new ArithmeticException();
3442 }
3443 return -x;
3444 }
3445
3446 /**
3447 * Negates the argument.
3448 * @param x number from which opposite value is requested
3449 * @return -x, or throws an exception for {@code Long.MIN_VALUE}
3450 * @since 2.0
3451 */
3452 public static long negateExact(final long x) {
3453 if (x == Long.MIN_VALUE) {
3454 throw new ArithmeticException();
3455 }
3456 return -x;
3457 }
3458
3459 /**
3460 * Compute least significant bit (Unit in Last Position) for a number.
3461 * @param x number from which ulp is requested
3462 * @return ulp(x)
3463 */
3464 public static double ulp(double x) {
3465 if (Double.isInfinite(x)) {
3466 return Double.POSITIVE_INFINITY;
3467 }
3468 return abs(x - Double.longBitsToDouble(Double.doubleToRawLongBits(x) ^ 1));
3469 }
3470
3471 /**
3472 * Compute least significant bit (Unit in Last Position) for a number.
3473 * @param x number from which ulp is requested
3474 * @return ulp(x)
3475 */
3476 public static float ulp(float x) {
3477 if (Float.isInfinite(x)) {
3478 return Float.POSITIVE_INFINITY;
3479 }
3480 return abs(x - Float.intBitsToFloat(Float.floatToRawIntBits(x) ^ 1));
3481 }
3482
3483 /**
3484 * Multiply a double number by a power of 2.
3485 * @param d number to multiply
3486 * @param n power of 2
3487 * @return d × 2<sup>n</sup>
3488 */
3489 public static double scalb(final double d, final int n) {
3490
3491 // first simple and fast handling when 2^n can be represented using normal numbers
3492 if ((n > -1023) && (n < 1024)) {
3493 return d * Double.longBitsToDouble(((long) (n + 1023)) << 52);
3494 }
3495
3496 // handle special cases
3497 if (Double.isNaN(d) || Double.isInfinite(d) || (d == 0)) {
3498 return d;
3499 }
3500 if (n < -2098) {
3501 return (d > 0) ? 0.0 : -0.0;
3502 }
3503 if (n > 2097) {
3504 return (d > 0) ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY;
3505 }
3506
3507 // decompose d
3508 final long bits = Double.doubleToRawLongBits(d);
3509 final long sign = bits & 0x8000000000000000L;
3510 int exponent = ((int) (bits >>> 52)) & 0x7ff;
3511 long mantissa = bits & 0x000fffffffffffffL;
3512
3513 // compute scaled exponent
3514 int scaledExponent = exponent + n;
3515
3516 if (n < 0) {
3517 // we are really in the case n <= -1023
3518 if (scaledExponent > 0) {
3519 // both the input and the result are normal numbers, we only adjust the exponent
3520 return Double.longBitsToDouble(sign | (((long) scaledExponent) << 52) | mantissa);
3521 } else if (scaledExponent > -53) {
3522 // the input is a normal number and the result is a subnormal number
3523
3524 // recover the hidden mantissa bit
3525 mantissa |= 1L << 52;
3526
3527 // scales down complete mantissa, hence losing least significant bits
3528 final long mostSignificantLostBit = mantissa & (1L << (-scaledExponent));
3529 mantissa >>>= 1 - scaledExponent;
3530 if (mostSignificantLostBit != 0) {
3531 // we need to add 1 bit to round up the result
3532 mantissa++;
3533 }
3534 return Double.longBitsToDouble(sign | mantissa);
3535
3536 } else {
3537 // no need to compute the mantissa, the number scales down to 0
3538 return (sign == 0L) ? 0.0 : -0.0;
3539 }
3540 } else {
3541 // we are really in the case n >= 1024
3542 if (exponent == 0) {
3543
3544 // the input number is subnormal, normalize it
3545 while ((mantissa >>> 52) != 1) {
3546 mantissa <<= 1;
3547 --scaledExponent;
3548 }
3549 ++scaledExponent;
3550 mantissa &= 0x000fffffffffffffL;
3551
3552 if (scaledExponent < 2047) {
3553 return Double.longBitsToDouble(sign | (((long) scaledExponent) << 52) | mantissa);
3554 } else {
3555 return (sign == 0L) ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY;
3556 }
3557
3558 } else if (scaledExponent < 2047) {
3559 return Double.longBitsToDouble(sign | (((long) scaledExponent) << 52) | mantissa);
3560 } else {
3561 return (sign == 0L) ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY;
3562 }
3563 }
3564
3565 }
3566
3567 /**
3568 * Multiply a float number by a power of 2.
3569 * @param f number to multiply
3570 * @param n power of 2
3571 * @return f × 2<sup>n</sup>
3572 */
3573 public static float scalb(final float f, final int n) {
3574
3575 // first simple and fast handling when 2^n can be represented using normal numbers
3576 if ((n > -127) && (n < 128)) {
3577 return f * Float.intBitsToFloat((n + 127) << 23);
3578 }
3579
3580 // handle special cases
3581 if (Float.isNaN(f) || Float.isInfinite(f) || (f == 0f)) {
3582 return f;
3583 }
3584 if (n < -277) {
3585 return (f > 0) ? 0.0f : -0.0f;
3586 }
3587 if (n > 276) {
3588 return (f > 0) ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY;
3589 }
3590
3591 // decompose f
3592 final int bits = Float.floatToIntBits(f);
3593 final int sign = bits & 0x80000000;
3594 int exponent = (bits >>> 23) & 0xff;
3595 int mantissa = bits & 0x007fffff;
3596
3597 // compute scaled exponent
3598 int scaledExponent = exponent + n;
3599
3600 if (n < 0) {
3601 // we are really in the case n <= -127
3602 if (scaledExponent > 0) {
3603 // both the input and the result are normal numbers, we only adjust the exponent
3604 return Float.intBitsToFloat(sign | (scaledExponent << 23) | mantissa);
3605 } else if (scaledExponent > -24) {
3606 // the input is a normal number and the result is a subnormal number
3607
3608 // recover the hidden mantissa bit
3609 mantissa |= 1 << 23;
3610
3611 // scales down complete mantissa, hence losing least significant bits
3612 final int mostSignificantLostBit = mantissa & (1 << (-scaledExponent));
3613 mantissa >>>= 1 - scaledExponent;
3614 if (mostSignificantLostBit != 0) {
3615 // we need to add 1 bit to round up the result
3616 mantissa++;
3617 }
3618 return Float.intBitsToFloat(sign | mantissa);
3619
3620 } else {
3621 // no need to compute the mantissa, the number scales down to 0
3622 return (sign == 0) ? 0.0f : -0.0f;
3623 }
3624 } else {
3625 // we are really in the case n >= 128
3626 if (exponent == 0) {
3627
3628 // the input number is subnormal, normalize it
3629 while ((mantissa >>> 23) != 1) {
3630 mantissa <<= 1;
3631 --scaledExponent;
3632 }
3633 ++scaledExponent;
3634 mantissa &= 0x007fffff;
3635
3636 if (scaledExponent < 255) {
3637 return Float.intBitsToFloat(sign | (scaledExponent << 23) | mantissa);
3638 } else {
3639 return (sign == 0) ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY;
3640 }
3641
3642 } else if (scaledExponent < 255) {
3643 return Float.intBitsToFloat(sign | (scaledExponent << 23) | mantissa);
3644 } else {
3645 return (sign == 0) ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY;
3646 }
3647 }
3648
3649 }
3650
3651 /**
3652 * Get the next machine representable number after a number, moving
3653 * in the direction of another number.
3654 * <p>
3655 * The ordering is as follows (increasing):
3656 * </p>
3657 * <ul>
3658 * <li>-INFINITY</li>
3659 * <li>-MAX_VALUE</li>
3660 * <li>-MIN_VALUE</li>
3661 * <li>-0.0</li>
3662 * <li>+0.0</li>
3663 * <li>+MIN_VALUE</li>
3664 * <li>+MAX_VALUE</li>
3665 * <li>+INFINITY</li>
3666 * </ul>
3667 * <p>
3668 * If arguments compare equal, then the second argument is returned.
3669 * </p>
3670 * <p>
3671 * If {@code direction} is greater than {@code d},
3672 * the smallest machine representable number strictly greater than
3673 * {@code d} is returned; if less, then the largest representable number
3674 * strictly less than {@code d} is returned.
3675 * </p>
3676 * <p>
3677 * If {@code d} is infinite and direction does not
3678 * bring it back to finite numbers, it is returned unchanged.
3679 * </p>
3680 *
3681 * @param d base number
3682 * @param direction (the only important thing is whether
3683 * {@code direction} is greater or smaller than {@code d})
3684 * @return the next machine representable number in the specified direction
3685 */
3686 public static double nextAfter(double d, double direction) {
3687
3688 // handling of some important special cases
3689 if (Double.isNaN(d) || Double.isNaN(direction)) {
3690 return Double.NaN;
3691 } else if (d == direction) {
3692 return direction;
3693 } else if (Double.isInfinite(d)) {
3694 return (d < 0) ? -Double.MAX_VALUE : Double.MAX_VALUE;
3695 } else if (d == 0) {
3696 return (direction < 0) ? -Double.MIN_VALUE : Double.MIN_VALUE;
3697 }
3698 // special cases MAX_VALUE to infinity and MIN_VALUE to 0
3699 // are handled just as normal numbers
3700 // can use raw bits since already dealt with infinity and NaN
3701 final long bits = Double.doubleToRawLongBits(d);
3702 final long sign = bits & 0x8000000000000000L;
3703 if ((direction < d) ^ (sign == 0L)) {
3704 return Double.longBitsToDouble(sign | ((bits & 0x7fffffffffffffffL) + 1));
3705 } else {
3706 return Double.longBitsToDouble(sign | ((bits & 0x7fffffffffffffffL) - 1));
3707 }
3708
3709 }
3710
3711 /**
3712 * Get the next machine representable number after a number, moving
3713 * in the direction of another number.
3714 * <p>* The ordering is as follows (increasing):</p>
3715 * <ul>
3716 * <li>-INFINITY</li>
3717 * <li>-MAX_VALUE</li>
3718 * <li>-MIN_VALUE</li>
3719 * <li>-0.0</li>
3720 * <li>+0.0</li>
3721 * <li>+MIN_VALUE</li>
3722 * <li>+MAX_VALUE</li>
3723 * <li>+INFINITY</li>
3724 * </ul>
3725 * <p>
3726 * If arguments compare equal, then the second argument is returned.
3727 * </p>
3728 * <p>
3729 * If {@code direction} is greater than {@code f},
3730 * the smallest machine representable number strictly greater than
3731 * {@code f} is returned; if less, then the largest representable number
3732 * strictly less than {@code f} is returned.
3733 * </p>
3734 * <p>
3735 * If {@code f} is infinite and direction does not
3736 * bring it back to finite numbers, it is returned unchanged.
3737 * </p>
3738 *
3739 * @param f base number
3740 * @param direction (the only important thing is whether
3741 * {@code direction} is greater or smaller than {@code f})
3742 * @return the next machine representable number in the specified direction
3743 */
3744 public static float nextAfter(final float f, final double direction) {
3745
3746 // handling of some important special cases
3747 if (Double.isNaN(f) || Double.isNaN(direction)) {
3748 return Float.NaN;
3749 } else if (f == direction) {
3750 return (float) direction;
3751 } else if (Float.isInfinite(f)) {
3752 return (f < 0f) ? -Float.MAX_VALUE : Float.MAX_VALUE;
3753 } else if (f == 0f) {
3754 return (direction < 0) ? -Float.MIN_VALUE : Float.MIN_VALUE;
3755 }
3756 // special cases MAX_VALUE to infinity and MIN_VALUE to 0
3757 // are handled just as normal numbers
3758
3759 final int bits = Float.floatToIntBits(f);
3760 final int sign = bits & 0x80000000;
3761 if ((direction < f) ^ (sign == 0)) {
3762 return Float.intBitsToFloat(sign | ((bits & 0x7fffffff) + 1));
3763 } else {
3764 return Float.intBitsToFloat(sign | ((bits & 0x7fffffff) - 1));
3765 }
3766
3767 }
3768
3769 /** Get the largest whole number smaller than x.
3770 * @param x number from which floor is requested
3771 * @return a double number f such that f is an integer f <= x < f + 1.0
3772 */
3773 public static double floor(double x) {
3774 long y;
3775
3776 if (Double.isNaN(x)) {
3777 return x;
3778 }
3779
3780 if (x >= TWO_POWER_52 || x <= -TWO_POWER_52) {
3781 return x;
3782 }
3783
3784 y = (long) x;
3785 if (x < 0 && y != x) {
3786 y--;
3787 }
3788
3789 if (y == 0) {
3790 return x*y;
3791 }
3792
3793 return y;
3794 }
3795
3796 /** Get the smallest whole number larger than x.
3797 * @param x number from which ceil is requested
3798 * @return a double number c such that c is an integer c - 1.0 < x <= c
3799 */
3800 public static double ceil(double x) {
3801 double y;
3802
3803 if (Double.isNaN(x)) {
3804 return x;
3805 }
3806
3807 y = floor(x);
3808 if (y == x) {
3809 return y;
3810 }
3811
3812 y += 1.0;
3813
3814 if (y == 0) {
3815 return x*y;
3816 }
3817
3818 return y;
3819 }
3820
3821 /** Get the whole number that is the nearest to x, or the even one if x is exactly half way between two integers.
3822 * @param x number from which nearest whole number is requested
3823 * @return a double number r such that r is an integer r - 0.5 <= x <= r + 0.5
3824 */
3825 public static double rint(double x) {
3826 double y = floor(x);
3827 double d = x - y;
3828
3829 if (d > 0.5) {
3830 if (y == -1.0) {
3831 return -0.0; // Preserve sign of operand
3832 }
3833 return y+1.0;
3834 }
3835 if (d < 0.5) {
3836 return y;
3837 }
3838
3839 /* half way, round to even */
3840 long z = (long) y;
3841 return (z & 1) == 0 ? y : y + 1.0;
3842 }
3843
3844 /** Get the closest long to x.
3845 * @param x number from which closest long is requested
3846 * @return closest long to x
3847 */
3848 public static long round(double x) {
3849 final long bits = Double.doubleToRawLongBits(x);
3850 final int biasedExp = ((int)(bits>>52)) & 0x7ff;
3851 // Shift to get rid of bits past comma except first one: will need to
3852 // 1-shift to the right to end up with correct magnitude.
3853 final int shift = (52 - 1 + Double.MAX_EXPONENT) - biasedExp;
3854 if ((shift & -64) == 0) {
3855 // shift in [0,63], so unbiased exp in [-12,51].
3856 long extendedMantissa = 0x0010000000000000L | (bits & 0x000fffffffffffffL);
3857 if (bits < 0) {
3858 extendedMantissa = -extendedMantissa;
3859 }
3860 // If value is positive and first bit past comma is 0, rounding
3861 // to lower integer, else to upper one, which is what "+1" and
3862 // then ">>1" do.
3863 return ((extendedMantissa >> shift) + 1L) >> 1;
3864 } else {
3865 // +-Infinity, NaN, or a mathematical integer.
3866 return (long) x;
3867 }
3868 }
3869
3870 /** Get the closest int to x.
3871 * @param x number from which closest int is requested
3872 * @return closest int to x
3873 */
3874 public static int round(final float x) {
3875 final int bits = Float.floatToRawIntBits(x);
3876 final int biasedExp = (bits>>23) & 0xff;
3877 // Shift to get rid of bits past comma except first one: will need to
3878 // 1-shift to the right to end up with correct magnitude.
3879 final int shift = (23 - 1 + Float.MAX_EXPONENT) - biasedExp;
3880 if ((shift & -32) == 0) {
3881 // shift in [0,31], so unbiased exp in [-9,22].
3882 int extendedMantissa = 0x00800000 | (bits & 0x007fffff);
3883 if (bits < 0) {
3884 extendedMantissa = -extendedMantissa;
3885 }
3886 // If value is positive and first bit past comma is 0, rounding
3887 // to lower integer, else to upper one, which is what "+1" and
3888 // then ">>1" do.
3889 return ((extendedMantissa >> shift) + 1) >> 1;
3890 } else {
3891 // +-Infinity, NaN, or a mathematical integer.
3892 return (int) x;
3893 }
3894 }
3895
3896 /** Compute the minimum of two values
3897 * @param a first value
3898 * @param b second value
3899 * @return a if a is lesser or equal to b, b otherwise
3900 */
3901 public static int min(final int a, final int b) {
3902 return (a <= b) ? a : b;
3903 }
3904
3905 /** Compute the minimum of two values
3906 * @param a first value
3907 * @param b second value
3908 * @return a if a is lesser or equal to b, b otherwise
3909 */
3910 public static long min(final long a, final long b) {
3911 return (a <= b) ? a : b;
3912 }
3913
3914 /** Compute the minimum of two values
3915 * @param a first value
3916 * @param b second value
3917 * @return a if a is lesser or equal to b, b otherwise
3918 */
3919 public static float min(final float a, final float b) {
3920 if (a > b) {
3921 return b;
3922 }
3923 if (a < b) {
3924 return a;
3925 }
3926 /* if either arg is NaN, return NaN */
3927 if (a != b) {
3928 return Float.NaN;
3929 }
3930 /* min(+0.0,-0.0) == -0.0 */
3931 /* 0x80000000 == Float.floatToRawIntBits(-0.0d) */
3932 int bits = Float.floatToRawIntBits(a);
3933 if (bits == 0x80000000) {
3934 return a;
3935 }
3936 return b;
3937 }
3938
3939 /** Compute the minimum of two values
3940 * @param a first value
3941 * @param b second value
3942 * @return a if a is lesser or equal to b, b otherwise
3943 */
3944 public static double min(final double a, final double b) {
3945 if (a > b) {
3946 return b;
3947 }
3948 if (a < b) {
3949 return a;
3950 }
3951 /* if either arg is NaN, return NaN */
3952 if (a != b) {
3953 return Double.NaN;
3954 }
3955 /* min(+0.0,-0.0) == -0.0 */
3956 /* 0x8000000000000000L == Double.doubleToRawLongBits(-0.0d) */
3957 long bits = Double.doubleToRawLongBits(a);
3958 if (bits == 0x8000000000000000L) {
3959 return a;
3960 }
3961 return b;
3962 }
3963
3964 /** Compute the maximum of two values
3965 * @param a first value
3966 * @param b second value
3967 * @return b if a is lesser or equal to b, a otherwise
3968 */
3969 public static int max(final int a, final int b) {
3970 return (a <= b) ? b : a;
3971 }
3972
3973 /** Compute the maximum of two values
3974 * @param a first value
3975 * @param b second value
3976 * @return b if a is lesser or equal to b, a otherwise
3977 */
3978 public static long max(final long a, final long b) {
3979 return (a <= b) ? b : a;
3980 }
3981
3982 /** Compute the maximum of two values
3983 * @param a first value
3984 * @param b second value
3985 * @return b if a is lesser or equal to b, a otherwise
3986 */
3987 public static float max(final float a, final float b) {
3988 if (a > b) {
3989 return a;
3990 }
3991 if (a < b) {
3992 return b;
3993 }
3994 /* if either arg is NaN, return NaN */
3995 if (a != b) {
3996 return Float.NaN;
3997 }
3998 /* min(+0.0,-0.0) == -0.0 */
3999 /* 0x80000000 == Float.floatToRawIntBits(-0.0d) */
4000 int bits = Float.floatToRawIntBits(a);
4001 if (bits == 0x80000000) {
4002 return b;
4003 }
4004 return a;
4005 }
4006
4007 /** Compute the maximum of two values
4008 * @param a first value
4009 * @param b second value
4010 * @return b if a is lesser or equal to b, a otherwise
4011 */
4012 public static double max(final double a, final double b) {
4013 if (a > b) {
4014 return a;
4015 }
4016 if (a < b) {
4017 return b;
4018 }
4019 /* if either arg is NaN, return NaN */
4020 if (a != b) {
4021 return Double.NaN;
4022 }
4023 /* min(+0.0,-0.0) == -0.0 */
4024 /* 0x8000000000000000L == Double.doubleToRawLongBits(-0.0d) */
4025 long bits = Double.doubleToRawLongBits(a);
4026 if (bits == 0x8000000000000000L) {
4027 return b;
4028 }
4029 return a;
4030 }
4031
4032 /**
4033 * Returns the hypotenuse of a triangle with sides {@code x} and {@code y}
4034 * - sqrt(<i>x</i><sup>2</sup> +<i>y</i><sup>2</sup>)<br>
4035 * avoiding intermediate overflow or underflow.
4036 *
4037 * <ul>
4038 * <li> If either argument is infinite, then the result is positive infinity.</li>
4039 * <li> else, if either argument is NaN then the result is NaN.</li>
4040 * </ul>
4041 *
4042 * @param x a value
4043 * @param y a value
4044 * @return sqrt(<i>x</i><sup>2</sup> +<i>y</i><sup>2</sup>)
4045 */
4046 public static double hypot(final double x, final double y) {
4047 if (Double.isInfinite(x) || Double.isInfinite(y)) {
4048 return Double.POSITIVE_INFINITY;
4049 } else if (Double.isNaN(x) || Double.isNaN(y)) {
4050 return Double.NaN;
4051 } else {
4052
4053 final int expX = getExponent(x);
4054 final int expY = getExponent(y);
4055 if (expX > expY + 27) {
4056 // y is neglectible with respect to x
4057 return abs(x);
4058 } else if (expY > expX + 27) {
4059 // x is neglectible with respect to y
4060 return abs(y);
4061 } else {
4062
4063 // find an intermediate scale to avoid both overflow and underflow
4064 final int middleExp = (expX + expY) / 2;
4065
4066 // scale parameters without losing precision
4067 final double scaledX = scalb(x, -middleExp);
4068 final double scaledY = scalb(y, -middleExp);
4069
4070 // compute scaled hypotenuse
4071 final double scaledH = sqrt(scaledX * scaledX + scaledY * scaledY);
4072
4073 // remove scaling
4074 return scalb(scaledH, middleExp);
4075
4076 }
4077
4078 }
4079 }
4080
4081 /**
4082 * Computes the remainder as prescribed by the IEEE 754 standard.
4083 * <p>
4084 * The remainder value is mathematically equal to {@code x - y*n}
4085 * where {@code n} is the mathematical integer closest to the exact mathematical value
4086 * of the quotient {@code x/y}.
4087 * If two mathematical integers are equally close to {@code x/y} then
4088 * {@code n} is the integer that is even.
4089 * </p>
4090 * <ul>
4091 * <li>If either operand is NaN, the result is NaN.</li>
4092 * <li>If the result is not NaN, the sign of the result equals the sign of the dividend.</li>
4093 * <li>If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN.</li>
4094 * <li>If the dividend is finite and the divisor is an infinity, the result equals the dividend.</li>
4095 * <li>If the dividend is a zero and the divisor is finite, the result equals the dividend.</li>
4096 * </ul>
4097 * @param dividend the number to be divided
4098 * @param divisor the number by which to divide
4099 * @return the remainder, rounded
4100 */
4101 public static double IEEEremainder(final double dividend, final double divisor) {
4102 if (getExponent(dividend) == 1024 || getExponent(divisor) == 1024 || divisor == 0.0) {
4103 // we are in one of the special cases
4104 if (Double.isInfinite(divisor) && !Double.isInfinite(dividend)) {
4105 return dividend;
4106 } else {
4107 return Double.NaN;
4108 }
4109 } else {
4110 // we are in the general case
4111 final double n = rint(dividend / divisor);
4112 final double remainder = Double.isInfinite(n) ? 0.0 : dividend - divisor * n;
4113 return (remainder == 0) ? copySign(remainder, dividend) : remainder;
4114 }
4115 }
4116
4117 /** Convert a long to interger, detecting overflows
4118 * @param n number to convert to int
4119 * @return integer with same valie as n if no overflows occur
4120 * @exception MathRuntimeException if n cannot fit into an int
4121 */
4122 public static int toIntExact(final long n) throws MathRuntimeException {
4123 if (n < Integer.MIN_VALUE || n > Integer.MAX_VALUE) {
4124 throw new MathRuntimeException(LocalizedCoreFormats.OVERFLOW);
4125 }
4126 return (int) n;
4127 }
4128
4129 /** Increment a number, detecting overflows.
4130 * @param n number to increment
4131 * @return n+1 if no overflows occur
4132 * @exception MathRuntimeException if an overflow occurs
4133 */
4134 public static int incrementExact(final int n) throws MathRuntimeException {
4135
4136 if (n == Integer.MAX_VALUE) {
4137 throw new MathRuntimeException(LocalizedCoreFormats.OVERFLOW_IN_ADDITION, n, 1);
4138 }
4139
4140 return n + 1;
4141
4142 }
4143
4144 /** Increment a number, detecting overflows.
4145 * @param n number to increment
4146 * @return n+1 if no overflows occur
4147 * @exception MathRuntimeException if an overflow occurs
4148 */
4149 public static long incrementExact(final long n) throws MathRuntimeException {
4150
4151 if (n == Long.MAX_VALUE) {
4152 throw new MathRuntimeException(LocalizedCoreFormats.OVERFLOW_IN_ADDITION, n, 1);
4153 }
4154
4155 return n + 1;
4156
4157 }
4158
4159 /** Decrement a number, detecting overflows.
4160 * @param n number to decrement
4161 * @return n-1 if no overflows occur
4162 * @exception MathRuntimeException if an overflow occurs
4163 */
4164 public static int decrementExact(final int n) throws MathRuntimeException {
4165
4166 if (n == Integer.MIN_VALUE) {
4167 throw new MathRuntimeException(LocalizedCoreFormats.OVERFLOW_IN_SUBTRACTION, n, 1);
4168 }
4169
4170 return n - 1;
4171
4172 }
4173
4174 /** Decrement a number, detecting overflows.
4175 * @param n number to decrement
4176 * @return n-1 if no overflows occur
4177 * @exception MathRuntimeException if an overflow occurs
4178 */
4179 public static long decrementExact(final long n) throws MathRuntimeException {
4180
4181 if (n == Long.MIN_VALUE) {
4182 throw new MathRuntimeException(LocalizedCoreFormats.OVERFLOW_IN_SUBTRACTION, n, 1);
4183 }
4184
4185 return n - 1;
4186
4187 }
4188
4189 /** Add two numbers, detecting overflows.
4190 * @param a first number to add
4191 * @param b second number to add
4192 * @return a+b if no overflows occur
4193 * @exception MathRuntimeException if an overflow occurs
4194 */
4195 public static int addExact(final int a, final int b) throws MathRuntimeException {
4196
4197 // compute sum
4198 final int sum = a + b;
4199
4200 // check for overflow
4201 if ((a ^ b) >= 0 && (sum ^ b) < 0) {
4202 throw new MathRuntimeException(LocalizedCoreFormats.OVERFLOW_IN_ADDITION, a, b);
4203 }
4204
4205 return sum;
4206
4207 }
4208
4209 /** Add two numbers, detecting overflows.
4210 * @param a first number to add
4211 * @param b second number to add
4212 * @return a+b if no overflows occur
4213 * @exception MathRuntimeException if an overflow occurs
4214 */
4215 public static long addExact(final long a, final long b) throws MathRuntimeException {
4216
4217 // compute sum
4218 final long sum = a + b;
4219
4220 // check for overflow
4221 if ((a ^ b) >= 0 && (sum ^ b) < 0) {
4222 throw new MathRuntimeException(LocalizedCoreFormats.OVERFLOW_IN_ADDITION, a, b);
4223 }
4224
4225 return sum;
4226
4227 }
4228
4229 /** Subtract two numbers, detecting overflows.
4230 * @param a first number
4231 * @param b second number to subtract from a
4232 * @return a-b if no overflows occur
4233 * @exception MathRuntimeException if an overflow occurs
4234 */
4235 public static int subtractExact(final int a, final int b) {
4236
4237 // compute subtraction
4238 final int sub = a - b;
4239
4240 // check for overflow
4241 if ((a ^ b) < 0 && (sub ^ b) >= 0) {
4242 throw new MathRuntimeException(LocalizedCoreFormats.OVERFLOW_IN_SUBTRACTION, a, b);
4243 }
4244
4245 return sub;
4246
4247 }
4248
4249 /** Subtract two numbers, detecting overflows.
4250 * @param a first number
4251 * @param b second number to subtract from a
4252 * @return a-b if no overflows occur
4253 * @exception MathRuntimeException if an overflow occurs
4254 */
4255 public static long subtractExact(final long a, final long b) {
4256
4257 // compute subtraction
4258 final long sub = a - b;
4259
4260 // check for overflow
4261 if ((a ^ b) < 0 && (sub ^ b) >= 0) {
4262 throw new MathRuntimeException(LocalizedCoreFormats.OVERFLOW_IN_SUBTRACTION, a, b);
4263 }
4264
4265 return sub;
4266
4267 }
4268
4269 /** Multiply two numbers, detecting overflows.
4270 * @param a first number to multiply
4271 * @param b second number to multiply
4272 * @return a*b if no overflows occur
4273 * @exception MathRuntimeException if an overflow occurs
4274 */
4275 public static int multiplyExact(final int a, final int b) {
4276 if (((b > 0) && (a > Integer.MAX_VALUE / b || a < Integer.MIN_VALUE / b)) ||
4277 ((b < -1) && (a > Integer.MIN_VALUE / b || a < Integer.MAX_VALUE / b)) ||
4278 ((b == -1) && (a == Integer.MIN_VALUE))) {
4279 throw new MathRuntimeException(LocalizedCoreFormats.OVERFLOW_IN_MULTIPLICATION, a, b);
4280 }
4281 return a * b;
4282 }
4283
4284 /** Multiply two numbers, detecting overflows.
4285 * @param a first number to multiply
4286 * @param b second number to multiply
4287 * @return a*b if no overflows occur
4288 * @exception MathRuntimeException if an overflow occurs
4289 * @since 1.3
4290 */
4291 public static long multiplyExact(final long a, final int b) {
4292 return multiplyExact(a, (long) b);
4293 }
4294
4295 /** Multiply two numbers, detecting overflows.
4296 * @param a first number to multiply
4297 * @param b second number to multiply
4298 * @return a*b if no overflows occur
4299 * @exception MathRuntimeException if an overflow occurs
4300 */
4301 public static long multiplyExact(final long a, final long b) {
4302 if (((b > 0l) && (a > Long.MAX_VALUE / b || a < Long.MIN_VALUE / b)) ||
4303 ((b < -1l) && (a > Long.MIN_VALUE / b || a < Long.MAX_VALUE / b)) ||
4304 ((b == -1l) && (a == Long.MIN_VALUE))) {
4305 throw new MathRuntimeException(LocalizedCoreFormats.OVERFLOW_IN_MULTIPLICATION, a, b);
4306 }
4307 return a * b;
4308 }
4309
4310 /** Multiply two integers and give an exact result without overflow.
4311 * @param a first factor
4312 * @param b second factor
4313 * @return a * b exactly
4314 * @since 1.3
4315 */
4316 public static long multiplyFull(final int a, final int b) {
4317 return ((long) a) * ((long) b); // NOPMD - casts are intentional here
4318 }
4319
4320 /** Multiply two long integers and give the 64 most significant bits of the result.
4321 * <p>
4322 * Beware that as Java primitive long are always considered to be signed, there are some
4323 * intermediate values {@code a} and {@code b} for which {@code a * b} exceeds {@code Long.MAX_VALUE}
4324 * but this method will still return 0l. This happens for example for {@code a = 2³¹} and
4325 * {@code b = 2³²} as {@code a * b = 2⁶³ = Long.MAX_VALUE + 1}, so it exceeds the max value
4326 * for a long, but still fits in 64 bits, so this method correctly returns 0l in this case,
4327 * but multiplication result would be considered negative (and in fact equal to {@code Long.MIN_VALUE}
4328 * </p>
4329 * @param a first factor
4330 * @param b second factor
4331 * @return a * b / 2<sup>64</sup>
4332 * @since 1.3
4333 */
4334 public static long multiplyHigh(final long a, final long b) {
4335
4336 // all computations below are performed on unsigned numbers because we start
4337 // by using logical shifts (and not arithmetic shifts). We will therefore
4338 // need to take care of sign before returning
4339 // a negative long n between -2⁶³ and -1, interpreted as an unsigned long
4340 // corresponds to 2⁶⁴ + n (which is between 2⁶³ and 2⁶⁴-1)
4341 // so if this number is multiplied by p, what we really compute
4342 // is (2⁶⁴ + n) * p = 2⁶⁴ * p + n * p, therefore the part above 64 bits
4343 // will have an extra term p that we will need to remove
4344 final long tobeRemoved = ((a < 0) ? b : 0) + ((b < 0) ? a : 0);
4345
4346 return unsignedMultiplyHigh(a, b) - tobeRemoved;
4347
4348 }
4349
4350 /** Multiply two long unsigned integers and give the 64 most significant bits of the unsigned result.
4351 * <p>
4352 * Beware that as Java primitive long are always considered to be signed, there are some
4353 * intermediate values {@code a} and {@code b} for which {@code a * b} exceeds {@code Long.MAX_VALUE}
4354 * but this method will still return 0l. This happens for example for {@code a = 2³¹} and
4355 * {@code b = 2³²} as {@code a * b = 2⁶³ = Long.MAX_VALUE + 1}, so it exceeds the max value
4356 * for a long, but still fits in 64 bits, so this method correctly returns 0l in this case,
4357 * but multiplication result would be considered negative (and in fact equal to {@code Long.MIN_VALUE}
4358 * </p>
4359 * @param a first factor
4360 * @param b second factor
4361 * @return a * b / 2<sup>64</sup>
4362 * @since 3.0
4363 */
4364 public static long unsignedMultiplyHigh(final long a, final long b) {
4365
4366 // split numbers in two 32 bits parts
4367 final long aHigh = a >>> 32;
4368 final long aLow = a & 0xFFFFFFFFL;
4369 final long bHigh = b >>> 32;
4370 final long bLow = b & 0xFFFFFFFFL;
4371
4372 // ab = aHigh * bHigh * 2⁶⁴ + (aHigh * bLow + aLow * bHigh) * 2³² + aLow * bLow
4373 final long hh = aHigh * bHigh;
4374 final long hl1 = aHigh * bLow;
4375 final long hl2 = aLow * bHigh;
4376 final long ll = aLow * bLow;
4377
4378 // adds up everything in the above 64 bit part, taking care to avoid overflow
4379 final long hlHigh = (hl1 >>> 32) + (hl2 >>> 32);
4380 final long hlLow = (hl1 & 0xFFFFFFFFL) + (hl2 & 0xFFFFFFFFL);
4381 final long carry = (hlLow + (ll >>> 32)) >>> 32;
4382
4383 return hh + hlHigh + carry;
4384
4385 }
4386
4387 /** Divide two integers, checking for overflow.
4388 * @param x dividend
4389 * @param y divisor
4390 * @return x / y
4391 * @exception MathRuntimeException if an overflow occurs
4392 * @since 3.0
4393 */
4394 public static int divideExact(final int x, final int y) {
4395 if (y == 0) {
4396 throw new MathRuntimeException(LocalizedCoreFormats.ZERO_DENOMINATOR);
4397 }
4398 if (y == -1 && x == Integer.MIN_VALUE) {
4399 throw new MathRuntimeException(LocalizedCoreFormats.OVERFLOW_IN_FRACTION, x, y);
4400 }
4401 return x / y;
4402 }
4403
4404 /** Divide two long integers, checking for overflow.
4405 * @param x dividend
4406 * @param y divisor
4407 * @return x / y
4408 * @exception MathRuntimeException if an overflow occurs
4409 * @since 3.0
4410 */
4411 public static long divideExact(final long x, final long y) {
4412 if (y == 0L) {
4413 throw new MathRuntimeException(LocalizedCoreFormats.ZERO_DENOMINATOR);
4414 }
4415 if (y == -1L && x == Long.MIN_VALUE) {
4416 throw new MathRuntimeException(LocalizedCoreFormats.OVERFLOW_IN_FRACTION, x, y);
4417 }
4418 return x / y;
4419 }
4420
4421 /** Finds q such that {@code a = q b + r} with {@code b < r <= 0} if {@code b > 0} and {@code 0 <= r < b} if {@code b < 0}.
4422 * <p>
4423 * This methods returns the same value as integer division when
4424 * a and b are opposite signs, but returns a different value when
4425 * they are same (i.e. q is positive).
4426 *
4427 * @param a dividend
4428 * @param b divisor
4429 * @return q such that {@code a = q b + r} with {@code b < r <= 0} if {@code b > 0} and {@code 0 <= r < b} if {@code b < 0}
4430 * @exception MathRuntimeException if b == 0
4431 * @since 3.0
4432 */
4433 public static int ceilDiv(final int a, final int b) throws MathRuntimeException {
4434
4435 if (b == 0) {
4436 throw new MathRuntimeException(LocalizedCoreFormats.ZERO_DENOMINATOR);
4437 }
4438
4439 final int m = a % b;
4440 if ((a ^ b) < 0 || m == 0) {
4441 // a and b have opposite signs, or division is exact
4442 return a / b;
4443 } else {
4444 // a and b have same signs and division is not exact
4445 return (a / b) + 1;
4446 }
4447
4448 }
4449
4450 /** Finds q such that {@code a = q b + r} with {@code b < r <= 0} if {@code b > 0} and {@code 0 <= r < b} if {@code b < 0}.
4451 * <p>
4452 * This methods returns the same value as integer division when
4453 * a and b are opposite signs, but returns a different value when
4454 * they are same (i.e. q is positive).
4455 *
4456 * @param a dividend
4457 * @param b divisor
4458 * @return q such that {@code a = q b + r} with {@code b < r <= 0} if {@code b > 0} and {@code 0 <= r < b} if {@code b < 0}
4459 * @exception MathRuntimeException if b == 0 or if a == {@code Integer.MIN_VALUE} and b = -1
4460 * @since 3.0
4461 */
4462 public static int ceilDivExact(final int a, final int b) throws MathRuntimeException {
4463
4464 if (a == Integer.MIN_VALUE && b == -1) {
4465 throw new MathRuntimeException(LocalizedCoreFormats.OVERFLOW_IN_FRACTION, a, b);
4466 }
4467
4468 return ceilDiv(a, b);
4469
4470 }
4471
4472 /** Finds q such that {@code a = q b + r} with {@code b < r <= 0} if {@code b > 0} and {@code 0 <= r < b} if {@code b < 0}.
4473 * <p>
4474 * This methods returns the same value as integer division when
4475 * a and b are opposite signs, but returns a different value when
4476 * they are same (i.e. q is positive).
4477 *
4478 * @param a dividend
4479 * @param b divisor
4480 * @return q such that {@code a = q b + r} with {@code b < r <= 0} if {@code b > 0} and {@code 0 <= r < b} if {@code b < 0}
4481 * @exception MathRuntimeException if b == 0
4482 * @since 3.0
4483 */
4484 public static long ceilDiv(final long a, final long b) throws MathRuntimeException {
4485
4486 if (b == 0L) {
4487 throw new MathRuntimeException(LocalizedCoreFormats.ZERO_DENOMINATOR);
4488 }
4489
4490 final long m = a % b;
4491 if ((a ^ b) < 0 || m == 0L) {
4492 // a and b have opposite signs, or division is exact
4493 return a / b;
4494 } else {
4495 // a and b have same signs and division is not exact
4496 return (a / b) + 1L;
4497 }
4498
4499 }
4500
4501 /** Finds q such that {@code a = q b + r} with {@code b < r <= 0} if {@code b > 0} and {@code 0 <= r < b} if {@code b < 0}.
4502 * <p>
4503 * This methods returns the same value as integer division when
4504 * a and b are opposite signs, but returns a different value when
4505 * they are same (i.e. q is positive).
4506 *
4507 * @param a dividend
4508 * @param b divisor
4509 * @return q such that {@code a = q b + r} with {@code b < r <= 0} if {@code b > 0} and {@code 0 <= r < b} if {@code b < 0}
4510 * @exception MathRuntimeException if b == 0 or if a == {@code Long.MIN_VALUE} and b = -1
4511 * @since 3.0
4512 */
4513 public static long ceilDivExact(final long a, final long b) throws MathRuntimeException {
4514
4515 if (a == Long.MIN_VALUE && b == -1L) {
4516 throw new MathRuntimeException(LocalizedCoreFormats.OVERFLOW_IN_FRACTION, a, b);
4517 }
4518
4519 return ceilDiv(a, b);
4520
4521 }
4522
4523 /** Finds q such that {@code a = q b + r} with {@code b < r <= 0} if {@code b > 0} and {@code 0 <= r < b} if {@code b < 0}.
4524 * <p>
4525 * This methods returns the same value as integer division when
4526 * a and b are opposite signs, but returns a different value when
4527 * they are same (i.e. q is positive).
4528 *
4529 * @param a dividend
4530 * @param b divisor
4531 * @return q such that {@code a = q b + r} with {@code b < r <= 0} if {@code b > 0} and {@code 0 <= r < b} if {@code b < 0}
4532 * @exception MathRuntimeException if b == 0
4533 * @since 3.0
4534 */
4535 public static long ceilDiv(final long a, final int b) throws MathRuntimeException {
4536 return ceilDiv(a, (long) b);
4537 }
4538
4539 /** Finds r such that {@code a = q b + r} with {@code b < r <= 0} if {@code b > 0} and {@code 0 <= r < b} if {@code b < 0}.
4540 * <p>
4541 * This methods returns the same value as integer modulo when
4542 * a and b are opposite signs, but returns a different value when
4543 * they are same (i.e. q is positive).
4544 *
4545 * @param a dividend
4546 * @param b divisor
4547 * @return r such that {@code a = q b + r} with {@code b < r <= 0} if {@code b > 0} and {@code 0 <= r < b} if {@code b < 0}
4548 * @exception MathRuntimeException if b == 0
4549 * @since 3.0
4550 */
4551 public static int ceilMod(final int a, final int b) throws MathRuntimeException {
4552
4553 if (b == 0) {
4554 throw new MathRuntimeException(LocalizedCoreFormats.ZERO_DENOMINATOR);
4555 }
4556
4557 final int m = a % b;
4558 if ((a ^ b) < 0 || m == 0) {
4559 // a and b have opposite signs, or division is exact
4560 return m;
4561 } else {
4562 // a and b have same signs and division is not exact
4563 return m - b;
4564 }
4565
4566 }
4567
4568 /** Finds r such that {@code a = q b + r} with {@code b < r <= 0} if {@code b > 0} and {@code 0 <= r < b} if {@code b < 0}.
4569 * <p>
4570 * This methods returns the same value as integer modulo when
4571 * a and b are opposite signs, but returns a different value when
4572 * they are same (i.e. q is positive).
4573 *
4574 * @param a dividend
4575 * @param b divisor
4576 * @return r such that {@code a = q b + r} with {@code b < r <= 0} if {@code b > 0} and {@code 0 <= r < b} if {@code b < 0}
4577 * @exception MathRuntimeException if b == 0
4578 * @since 3.0
4579 */
4580 public static int ceilMod(final long a, final int b) throws MathRuntimeException {
4581 return (int) ceilMod(a, (long) b);
4582 }
4583
4584 /** Finds r such that {@code a = q b + r} with {@code b < r <= 0} if {@code b > 0} and {@code 0 <= r < b} if {@code b < 0}.
4585 * <p>
4586 * This methods returns the same value as integer modulo when
4587 * a and b are opposite signs, but returns a different value when
4588 * they are same (i.e. q is positive).
4589 *
4590 * @param a dividend
4591 * @param b divisor
4592 * @return r such that {@code a = q b + r} with {@code b < r <= 0} if {@code b > 0} and {@code 0 <= r < b} if {@code b < 0}
4593 * @exception MathRuntimeException if b == 0
4594 * @since 3.0
4595 */
4596 public static long ceilMod(final long a, final long b) throws MathRuntimeException {
4597
4598 if (b == 0L) {
4599 throw new MathRuntimeException(LocalizedCoreFormats.ZERO_DENOMINATOR);
4600 }
4601
4602 final long m = a % b;
4603 if ((a ^ b) < 0L || m == 0L) {
4604 // a and b have opposite signs, or division is exact
4605 return m;
4606 } else {
4607 // a and b have same signs and division is not exact
4608 return m - b;
4609 }
4610
4611 }
4612
4613 /** Finds q such that {@code a = q b + r} with {@code 0 <= r < b} if {@code b > 0} and {@code b < r <= 0} if {@code b < 0}.
4614 * <p>
4615 * This methods returns the same value as integer division when
4616 * a and b are same signs, but returns a different value when
4617 * they are opposite (i.e. q is negative).
4618 *
4619 * @param a dividend
4620 * @param b divisor
4621 * @return q such that {@code a = q b + r} with {@code 0 <= r < b} if {@code b > 0} and {@code b < r <= 0} if {@code b < 0}
4622 * @exception MathRuntimeException if b == 0
4623 * @see #floorMod(int, int)
4624 */
4625 public static int floorDiv(final int a, final int b) throws MathRuntimeException {
4626
4627 if (b == 0) {
4628 throw new MathRuntimeException(LocalizedCoreFormats.ZERO_DENOMINATOR);
4629 }
4630
4631 final int m = a % b;
4632 if ((a ^ b) >= 0 || m == 0) {
4633 // a and b have same sign, or division is exact
4634 return a / b;
4635 } else {
4636 // a and b have opposite signs and division is not exact
4637 return (a / b) - 1;
4638 }
4639
4640 }
4641
4642 /** Finds q such that {@code a = q b + r} with {@code 0 <= r < b} if {@code b > 0} and {@code b < r <= 0} if {@code b < 0}.
4643 * <p>
4644 * This methods returns the same value as integer division when
4645 * a and b are same signs, but returns a different value when
4646 * they are opposite (i.e. q is negative).
4647 *
4648 * @param a dividend
4649 * @param b divisor
4650 * @return q such that {@code a = q b + r} with {@code 0 <= r < b} if {@code b > 0} and {@code b < r <= 0} if {@code b < 0}
4651 * @exception MathRuntimeException if b == 0 or if a == {@code Integer.MIN_VALUE} and b = -1
4652 * @see #floorMod(int, int)
4653 * @since 3.0
4654 */
4655 public static int floorDivExact(final int a, final int b) throws MathRuntimeException {
4656
4657 if (a == Integer.MIN_VALUE && b == -1) {
4658 throw new MathRuntimeException(LocalizedCoreFormats.OVERFLOW_IN_FRACTION, a, b);
4659 }
4660
4661 return floorDiv(a, b);
4662
4663 }
4664
4665 /** Finds q such that {@code a = q b + r} with {@code 0 <= r < b} if {@code b > 0} and {@code b < r <= 0} if {@code b < 0}.
4666 * <p>
4667 * This methods returns the same value as integer division when
4668 * a and b are same signs, but returns a different value when
4669 * they are opposite (i.e. q is negative).
4670 *
4671 * @param a dividend
4672 * @param b divisor
4673 * @return q such that {@code a = q b + r} with {@code 0 <= r < b} if {@code b > 0} and {@code b < r <= 0} if {@code b < 0}
4674 * @exception MathRuntimeException if b == 0
4675 * @see #floorMod(long, int)
4676 * @since 1.3
4677 */
4678 public static long floorDiv(final long a, final int b) throws MathRuntimeException {
4679 return floorDiv(a, (long) b);
4680 }
4681
4682 /** Finds q such that {@code a = q b + r} with {@code 0 <= r < b} if {@code b > 0} and {@code b < r <= 0} if {@code b < 0}.
4683 * <p>
4684 * This methods returns the same value as integer division when
4685 * a and b are same signs, but returns a different value when
4686 * they are opposite (i.e. q is negative).
4687 *
4688 * @param a dividend
4689 * @param b divisor
4690 * @return q such that {@code a = q b + r} with {@code 0 <= r < b} if {@code b > 0} and {@code b < r <= 0} if {@code b < 0}
4691 * @exception MathRuntimeException if b == 0
4692 * @see #floorMod(long, long)
4693 */
4694 public static long floorDiv(final long a, final long b) throws MathRuntimeException {
4695
4696 if (b == 0L) {
4697 throw new MathRuntimeException(LocalizedCoreFormats.ZERO_DENOMINATOR);
4698 }
4699
4700 final long m = a % b;
4701 if ((a ^ b) >= 0L || m == 0L) {
4702 // a and b have same sign, or division is exact
4703 return a / b;
4704 } else {
4705 // a and b have opposite signs and division is not exact
4706 return (a / b) - 1L;
4707 }
4708
4709 }
4710
4711 /** Finds q such that {@code a = q b + r} with {@code 0 <= r < b} if {@code b > 0} and {@code b < r <= 0} if {@code b < 0}.
4712 * <p>
4713 * This methods returns the same value as integer division when
4714 * a and b are same signs, but returns a different value when
4715 * they are opposite (i.e. q is negative).
4716 *
4717 * @param a dividend
4718 * @param b divisor
4719 * @return q such that {@code a = q b + r} with {@code 0 <= r < b} if {@code b > 0} and {@code b < r <= 0} if {@code b < 0}
4720 * @exception MathRuntimeException if b == 0 or if a == {@code Long.MIN_VALUE} and b = -1
4721 * @see #floorMod(long, long)
4722 * @since 3.0
4723 */
4724 public static long floorDivExact(final long a, final long b) throws MathRuntimeException {
4725
4726 if (a == Long.MIN_VALUE && b == -1L) {
4727 throw new MathRuntimeException(LocalizedCoreFormats.OVERFLOW_IN_FRACTION, a, b);
4728 }
4729
4730 return floorDiv(a, b);
4731
4732 }
4733
4734 /** Finds r such that {@code a = q b + r} with {@code 0 <= r < b} if {@code b > 0} and {@code b < r <= 0} if {@code b < 0}.
4735 * <p>
4736 * This methods returns the same value as integer modulo when
4737 * a and b are same signs, but returns a different value when
4738 * they are opposite (i.e. q is negative).
4739 * </p>
4740 * @param a dividend
4741 * @param b divisor
4742 * @return r such that {@code a = q b + r} with {@code 0 <= r < b} if {@code b > 0} and {@code b < r <= 0} if {@code b < 0}
4743 * @exception MathRuntimeException if b == 0
4744 * @see #floorDiv(int, int)
4745 */
4746 public static int floorMod(final int a, final int b) throws MathRuntimeException {
4747
4748 if (b == 0) {
4749 throw new MathRuntimeException(LocalizedCoreFormats.ZERO_DENOMINATOR);
4750 }
4751
4752 final int m = a % b;
4753 if ((a ^ b) >= 0 || m == 0) {
4754 // a and b have same sign, or division is exact
4755 return m;
4756 } else {
4757 // a and b have opposite signs and division is not exact
4758 return b + m;
4759 }
4760
4761 }
4762
4763 /** Finds r such that {@code a = q b + r} with {@code 0 <= r < b} if {@code b > 0} and {@code b < r <= 0} if {@code b < 0}.
4764 * <p>
4765 * This methods returns the same value as integer modulo when
4766 * a and b are same signs, but returns a different value when
4767 * they are opposite (i.e. q is negative).
4768 * </p>
4769 * @param a dividend
4770 * @param b divisor
4771 * @return r such that {@code a = q b + r} with {@code 0 <= r < b} if {@code b > 0} and {@code b < r <= 0} if {@code b < 0}
4772 * @exception MathRuntimeException if b == 0
4773 * @see #floorDiv(long, int)
4774 * @since 1.3
4775 */
4776 public static int floorMod(final long a, final int b) {
4777 return (int) floorMod(a, (long) b);
4778 }
4779
4780 /** Finds r such that {@code a = q b + r} with {@code 0 <= r < b} if {@code b > 0} and {@code b < r <= 0} if {@code b < 0}.
4781 * <p>
4782 * This methods returns the same value as integer modulo when
4783 * a and b are same signs, but returns a different value when
4784 * they are opposite (i.e. q is negative).
4785 * </p>
4786 * @param a dividend
4787 * @param b divisor
4788 * @return r such that {@code a = q b + r} with {@code 0 <= r < b} if {@code b > 0} and {@code b < r <= 0} if {@code b < 0}
4789 * @exception MathRuntimeException if b == 0
4790 * @see #floorDiv(long, long)
4791 */
4792 public static long floorMod(final long a, final long b) {
4793
4794 if (b == 0L) {
4795 throw new MathRuntimeException(LocalizedCoreFormats.ZERO_DENOMINATOR);
4796 }
4797
4798 final long m = a % b;
4799 if ((a ^ b) >= 0L || m == 0L) {
4800 // a and b have same sign, or division is exact
4801 return m;
4802 } else {
4803 // a and b have opposite signs and division is not exact
4804 return b + m;
4805 }
4806
4807 }
4808
4809 /**
4810 * Returns the first argument with the sign of the second argument.
4811 * A NaN {@code sign} argument is treated as positive.
4812 *
4813 * @param magnitude the value to return
4814 * @param sign the sign for the returned value
4815 * @return the magnitude with the same sign as the {@code sign} argument
4816 */
4817 public static double copySign(double magnitude, double sign){
4818 // The highest order bit is going to be zero if the
4819 // highest order bit of m and s is the same and one otherwise.
4820 // So (m^s) will be positive if both m and s have the same sign
4821 // and negative otherwise.
4822 final long m = Double.doubleToRawLongBits(magnitude); // don't care about NaN
4823 final long s = Double.doubleToRawLongBits(sign);
4824 if ((m ^ s) >= 0) {
4825 return magnitude;
4826 }
4827 return -magnitude; // flip sign
4828 }
4829
4830 /**
4831 * Returns the first argument with the sign of the second argument.
4832 * A NaN {@code sign} argument is treated as positive.
4833 *
4834 * @param magnitude the value to return
4835 * @param sign the sign for the returned value
4836 * @return the magnitude with the same sign as the {@code sign} argument
4837 */
4838 public static float copySign(float magnitude, float sign){
4839 // The highest order bit is going to be zero if the
4840 // highest order bit of m and s is the same and one otherwise.
4841 // So (m^s) will be positive if both m and s have the same sign
4842 // and negative otherwise.
4843 final int m = Float.floatToRawIntBits(magnitude);
4844 final int s = Float.floatToRawIntBits(sign);
4845 if ((m ^ s) >= 0) {
4846 return magnitude;
4847 }
4848 return -magnitude; // flip sign
4849 }
4850
4851 /**
4852 * Return the exponent of a double number, removing the bias.
4853 * <p>
4854 * For double numbers of the form 2<sup>x</sup>, the unbiased
4855 * exponent is exactly x.
4856 * </p>
4857 * @param d number from which exponent is requested
4858 * @return exponent for d in IEEE754 representation, without bias
4859 */
4860 public static int getExponent(final double d) {
4861 // NaN and Infinite will return 1024 anyhow so can use raw bits
4862 return (int) ((Double.doubleToRawLongBits(d) >>> 52) & 0x7ff) - 1023;
4863 }
4864
4865 /**
4866 * Return the exponent of a float number, removing the bias.
4867 * <p>
4868 * For float numbers of the form 2<sup>x</sup>, the unbiased
4869 * exponent is exactly x.
4870 * </p>
4871 * @param f number from which exponent is requested
4872 * @return exponent for d in IEEE754 representation, without bias
4873 */
4874 public static int getExponent(final float f) {
4875 // NaN and Infinite will return the same exponent anyhow so can use raw bits
4876 return ((Float.floatToRawIntBits(f) >>> 23) & 0xff) - 127;
4877 }
4878
4879 /**
4880 * Unsigned product of unsigned arguments.
4881 * @param a first multiplicand
4882 * @param b second multiplicand
4883 * @return product of a and b, considered unsigned, throwing an exception in case of overflow
4884 * @since 4.1
4885 */
4886 public static int unsignedMultiplyExact(int a, int b) {
4887 if (a >= 0 && b >= 0) {
4888 int result;
4889 try {
4890 result = ArithmeticUtils.mulAndCheck(a, b);
4891 } catch (MathRuntimeException mre) {
4892 result = -1;
4893 }
4894 if (result >= 0) {
4895 return result;
4896 }
4897 }
4898 throw new ArithmeticException();
4899 }
4900
4901 /**
4902 * Unsigned product of unsigned arguments.
4903 * @param a first multiplicand
4904 * @param b second multiplicand
4905 * @return product of a and b, considered unsigned, throwing an exception in case of overflow
4906 * @since 4.1
4907 */
4908 public static long unsignedMultiplyExact(long a , int b) {
4909 return unsignedMultiplyExact(a, (long) b);
4910 }
4911
4912 /**
4913 * Unsigned product of unsigned arguments.
4914 * @param a first multiplicand
4915 * @param b second multiplicand
4916 * @return product of a and b, considered unsigned, throwing an exception in case of overflow
4917 * @since 4.1
4918 */
4919 public static long unsignedMultiplyExact(long a, long b) {
4920 if (a >= 0L && b >= 0L) {
4921 long result;
4922 try {
4923 result = ArithmeticUtils.mulAndCheck(a, b);
4924 } catch (MathRuntimeException mre) {
4925 result = -1L;
4926 }
4927 if (result >= 0L) {
4928 return result;
4929 }
4930 }
4931 throw new ArithmeticException();
4932 }
4933
4934 /**
4935 * Power function.
4936 * @param k base number
4937 * @param e exponent
4938 * @return b^e, throwing an exception in case of overflow
4939 * @since 4.1
4940 */
4941 public static int powExact(int k, int e) {
4942 try {
4943 return ArithmeticUtils.pow(k, e);
4944 } catch (MathRuntimeException mre) {
4945 throw new ArithmeticException();
4946 }
4947 }
4948
4949 /**
4950 * Power function.
4951 * @param k base number
4952 * @param e exponent
4953 * @return b^e, throwing an exception in case of overflow
4954 * @since 4.1
4955 */
4956 public static long powExact(long k, int e) {
4957 try {
4958 return ArithmeticUtils.pow(k, e);
4959 } catch (MathRuntimeException mre) {
4960 throw new ArithmeticException();
4961 }
4962 }
4963
4964 /**
4965 * Power function.
4966 * @param k base number
4967 * @param e exponent
4968 * @return b^e, throwing an exception in case of overflow
4969 * @since 4.1
4970 */
4971 public static int unsignedPowExact(int k, int e) {
4972 try {
4973 if (e == 0) {
4974 // process special case early (not event checking for k really be unsigned
4975 return 1;
4976 }
4977 if (k < 0) {
4978 // k is not unsigned
4979 throw new ArithmeticException();
4980 }
4981 return ArithmeticUtils.pow(k, e);
4982 } catch (MathRuntimeException mre) {
4983 throw new ArithmeticException();
4984 }
4985 }
4986
4987 /**
4988 * Power function.
4989 * @param k base number
4990 * @param e exponent
4991 * @return b^e, throwing an exception in case of overflow
4992 * @since 4.1
4993 */
4994 public static long unsignedPowExact(long k, int e) {
4995 try {
4996 if (e == 0) {
4997 // process special case early (not event checking for k really be unsigned
4998 return 1;
4999 }
5000 if (k < 0) {
5001 // k is not unsigned
5002 throw new ArithmeticException();
5003 }
5004 return ArithmeticUtils.pow(k, e);
5005 } catch (MathRuntimeException mre) {
5006 throw new ArithmeticException();
5007 }
5008 }
5009
5010 /** Compute Fused-multiply-add operation a * b + c.
5011 * <p>
5012 * This method was introduced in the regular {@code Math} and {@code StrictMath}
5013 * methods with Java 9, and then added to Hipparchus for consistency. However,
5014 * a more general method was available in Hipparchus that also allow to repeat
5015 * this computation across several terms: {@link MathArrays#linearCombination(double[], double[])}.
5016 * The linear combination method should probably be preferred in most cases.
5017 * </p>
5018 * @param a first factor
5019 * @param b second factor
5020 * @param c additive term
5021 * @return a * b + c, using extended precision in the multiplication
5022 * @see MathArrays#linearCombination(double[], double[])
5023 * @see MathArrays#linearCombination(double, double, double, double)
5024 * @see MathArrays#linearCombination(double, double, double, double, double, double)
5025 * @see MathArrays#linearCombination(double, double, double, double, double, double, double, double)
5026 * @since 1.3
5027 */
5028 public static double fma(final double a, final double b, final double c) {
5029 return MathArrays.linearCombination(a, b, 1.0, c);
5030 }
5031
5032 /** Compute Fused-multiply-add operation a * b + c.
5033 * <p>
5034 * This method was introduced in the regular {@code Math} and {@code StrictMath}
5035 * methods with Java 9, and then added to Hipparchus for consistency. However,
5036 * a more general method was available in Hipparchus that also allow to repeat
5037 * this computation across several terms: {@link MathArrays#linearCombination(double[], double[])}.
5038 * The linear combination method should probably be preferred in most cases.
5039 * </p>
5040 * @param a first factor
5041 * @param b second factor
5042 * @param c additive term
5043 * @return a * b + c, using extended precision in the multiplication
5044 * @see MathArrays#linearCombination(double[], double[])
5045 * @see MathArrays#linearCombination(double, double, double, double)
5046 * @see MathArrays#linearCombination(double, double, double, double, double, double)
5047 * @see MathArrays#linearCombination(double, double, double, double, double, double, double, double)
5048 */
5049 public static float fma(final float a, final float b, final float c) {
5050 return (float) MathArrays.linearCombination(a, b, 1.0, c);
5051 }
5052
5053 /** Compute the square root of a number.
5054 * @param a number on which evaluation is done
5055 * @param <T> the type of the field element
5056 * @return square root of a
5057 * @since 1.3
5058 */
5059 public static <T extends CalculusFieldElement<T>> T sqrt(final T a) {
5060 return a.sqrt();
5061 }
5062
5063 /** Compute the hyperbolic cosine of a number.
5064 * @param x number on which evaluation is done
5065 * @param <T> the type of the field element
5066 * @return hyperbolic cosine of x
5067 * @since 1.3
5068 */
5069 public static <T extends CalculusFieldElement<T>> T cosh(final T x) {
5070 return x.cosh();
5071 }
5072
5073 /** Compute the hyperbolic sine of a number.
5074 * @param x number on which evaluation is done
5075 * @param <T> the type of the field element
5076 * @return hyperbolic sine of x
5077 * @since 1.3
5078 */
5079 public static <T extends CalculusFieldElement<T>> T sinh(final T x) {
5080 return x.sinh();
5081 }
5082
5083 /** Compute the hyperbolic tangent of a number.
5084 * @param x number on which evaluation is done
5085 * @param <T> the type of the field element
5086 * @return hyperbolic tangent of x
5087 * @since 1.3
5088 */
5089 public static <T extends CalculusFieldElement<T>> T tanh(final T x) {
5090 return x.tanh();
5091 }
5092
5093 /** Compute the inverse hyperbolic cosine of a number.
5094 * @param a number on which evaluation is done
5095 * @param <T> the type of the field element
5096 * @return inverse hyperbolic cosine of a
5097 * @since 1.3
5098 */
5099 public static <T extends CalculusFieldElement<T>> T acosh(final T a) {
5100 return a.acosh();
5101 }
5102
5103 /** Compute the inverse hyperbolic sine of a number.
5104 * @param a number on which evaluation is done
5105 * @param <T> the type of the field element
5106 * @return inverse hyperbolic sine of a
5107 * @since 1.3
5108 */
5109 public static <T extends CalculusFieldElement<T>> T asinh(final T a) {
5110 return a.asinh();
5111 }
5112
5113 /** Compute the inverse hyperbolic tangent of a number.
5114 * @param a number on which evaluation is done
5115 * @param <T> the type of the field element
5116 * @return inverse hyperbolic tangent of a
5117 * @since 1.3
5118 */
5119 public static <T extends CalculusFieldElement<T>> T atanh(final T a) {
5120 return a.atanh();
5121 }
5122
5123 /** Compute the sign of a number.
5124 * The sign is -1 for negative numbers, +1 for positive numbers and 0 otherwise,
5125 * for Complex number, it is extended on the unit circle (equivalent to z/|z|,
5126 * with special handling for 0 and NaN)
5127 * @param a number on which evaluation is done
5128 * @param <T> the type of the field element
5129 * @return -1.0, -0.0, +0.0, +1.0 or NaN depending on sign of a
5130 * @since 2.0
5131 */
5132 public static <T extends CalculusFieldElement<T>> T sign(final T a) {
5133 return a.sign();
5134 }
5135
5136 /**
5137 * Exponential function.
5138 *
5139 * Computes exp(x), function result is nearly rounded. It will be correctly
5140 * rounded to the theoretical value for 99.9% of input values, otherwise it will
5141 * have a 1 ULP error.
5142 *
5143 * Method:
5144 * Lookup intVal = exp(int(x))
5145 * Lookup fracVal = exp(int(x-int(x) / 1024.0) * 1024.0 );
5146 * Compute z as the exponential of the remaining bits by a polynomial minus one
5147 * exp(x) = intVal * fracVal * (1 + z)
5148 *
5149 * Accuracy:
5150 * Calculation is done with 63 bits of precision, so result should be correctly
5151 * rounded for 99.9% of input values, with less than 1 ULP error otherwise.
5152 *
5153 * @param x a double
5154 * @param <T> the type of the field element
5155 * @return double e<sup>x</sup>
5156 * @since 1.3
5157 */
5158 public static <T extends CalculusFieldElement<T>> T exp(final T x) {
5159 return x.exp();
5160 }
5161
5162 /** Compute exp(x) - 1
5163 * @param x number to compute shifted exponential
5164 * @param <T> the type of the field element
5165 * @return exp(x) - 1
5166 * @since 1.3
5167 */
5168 public static <T extends CalculusFieldElement<T>> T expm1(final T x) {
5169 return x.expm1();
5170 }
5171
5172 /**
5173 * Natural logarithm.
5174 *
5175 * @param x a double
5176 * @param <T> the type of the field element
5177 * @return log(x)
5178 * @since 1.3
5179 */
5180 public static <T extends CalculusFieldElement<T>> T log(final T x) {
5181 return x.log();
5182 }
5183
5184 /**
5185 * Computes log(1 + x).
5186 *
5187 * @param x Number.
5188 * @param <T> the type of the field element
5189 * @return {@code log(1 + x)}.
5190 * @since 1.3
5191 */
5192 public static <T extends CalculusFieldElement<T>> T log1p(final T x) {
5193 return x.log1p();
5194 }
5195
5196 /** Compute the base 10 logarithm.
5197 * @param x a number
5198 * @param <T> the type of the field element
5199 * @return log10(x)
5200 * @since 1.3
5201 */
5202 public static <T extends CalculusFieldElement<T>> T log10(final T x) {
5203 return x.log10();
5204 }
5205
5206 /**
5207 * Power function. Compute x<sup>y</sup>.
5208 *
5209 * @param x a double
5210 * @param y a double
5211 * @param <T> the type of the field element
5212 * @return x<sup>y</sup>
5213 * @since 1.3
5214 */
5215 public static <T extends CalculusFieldElement<T>> T pow(final T x, final T y) {
5216 return x.pow(y);
5217 }
5218
5219 /**
5220 * Power function. Compute x<sup>y</sup>.
5221 *
5222 * @param x a double
5223 * @param y a double
5224 * @param <T> the type of the field element
5225 * @return x<sup>y</sup>
5226 * @since 1.7
5227 */
5228 public static <T extends CalculusFieldElement<T>> T pow(final T x, final double y) {
5229 return x.pow(y);
5230 }
5231
5232 /**
5233 * Raise a double to an int power.
5234 *
5235 * @param d Number to raise.
5236 * @param e Exponent.
5237 * @param <T> the type of the field element
5238 * @return d<sup>e</sup>
5239 * @since 1.3
5240 */
5241 public static <T extends CalculusFieldElement<T>> T pow(T d, int e) {
5242 return d.pow(e);
5243 }
5244
5245 /**
5246 * Sine function.
5247 *
5248 * @param x Argument.
5249 * @param <T> the type of the field element
5250 * @return sin(x)
5251 * @since 1.3
5252 */
5253 public static <T extends CalculusFieldElement<T>> T sin(final T x) {
5254 return x.sin();
5255 }
5256
5257 /**
5258 * Cosine function.
5259 *
5260 * @param x Argument.
5261 * @param <T> the type of the field element
5262 * @return cos(x)
5263 * @since 1.3
5264 */
5265 public static <T extends CalculusFieldElement<T>> T cos(final T x) {
5266 return x.cos();
5267 }
5268
5269 /**
5270 * Tangent function.
5271 *
5272 * @param x Argument.
5273 * @param <T> the type of the field element
5274 * @return tan(x)
5275 * @since 1.3
5276 */
5277 public static <T extends CalculusFieldElement<T>> T tan(final T x) {
5278 return x.tan();
5279 }
5280
5281 /**
5282 * Arctangent function
5283 * @param x a number
5284 * @param <T> the type of the field element
5285 * @return atan(x)
5286 * @since 1.3
5287 */
5288 public static <T extends CalculusFieldElement<T>> T atan(final T x) {
5289 return x.atan();
5290 }
5291
5292 /**
5293 * Two arguments arctangent function
5294 * @param y ordinate
5295 * @param x abscissa
5296 * @param <T> the type of the field element
5297 * @return phase angle of point (x,y) between {@code -PI} and {@code PI}
5298 * @since 1.3
5299 */
5300 public static <T extends CalculusFieldElement<T>> T atan2(final T y, final T x) {
5301 return y.atan2(x);
5302 }
5303
5304 /** Compute the arc sine of a number.
5305 * @param x number on which evaluation is done
5306 * @param <T> the type of the field element
5307 * @return arc sine of x
5308 * @since 1.3
5309 */
5310 public static <T extends CalculusFieldElement<T>> T asin(final T x) {
5311 return x.asin();
5312 }
5313
5314 /** Compute the arc cosine of a number.
5315 * @param x number on which evaluation is done
5316 * @param <T> the type of the field element
5317 * @return arc cosine of x
5318 * @since 1.3
5319 */
5320 public static <T extends CalculusFieldElement<T>> T acos(final T x) {
5321 return x.acos();
5322 }
5323
5324 /** Compute the cubic root of a number.
5325 * @param x number on which evaluation is done
5326 * @param <T> the type of the field element
5327 * @return cubic root of x
5328 * @since 1.3
5329 */
5330 public static <T extends CalculusFieldElement<T>> T cbrt(final T x) {
5331 return x.cbrt();
5332 }
5333
5334 /**
5335 * Norm.
5336 * @param x number from which norm is requested
5337 * @param <T> the type of the field element
5338 * @return norm(x)
5339 * @since 2.0
5340 */
5341 public static <T extends CalculusFieldElement<T>> double norm(final T x) {
5342 return x.norm();
5343 }
5344
5345 /**
5346 * Absolute value.
5347 * @param x number from which absolute value is requested
5348 * @param <T> the type of the field element
5349 * @return abs(x)
5350 * @since 2.0
5351 */
5352 public static <T extends CalculusFieldElement<T>> T abs(final T x) {
5353 return x.abs();
5354 }
5355
5356 /**
5357 * Convert degrees to radians, with error of less than 0.5 ULP
5358 * @param x angle in degrees
5359 * @param <T> the type of the field element
5360 * @return x converted into radians
5361 */
5362 public static <T extends CalculusFieldElement<T>> T toRadians(T x) {
5363 return x.toRadians();
5364 }
5365
5366 /**
5367 * Convert radians to degrees, with error of less than 0.5 ULP
5368 * @param x angle in radians
5369 * @param <T> the type of the field element
5370 * @return x converted into degrees
5371 */
5372 public static <T extends CalculusFieldElement<T>> T toDegrees(T x) {
5373 return x.toDegrees();
5374 }
5375
5376 /**
5377 * Multiply a double number by a power of 2.
5378 * @param d number to multiply
5379 * @param n power of 2
5380 * @param <T> the type of the field element
5381 * @return d × 2<sup>n</sup>
5382 * @since 1.3
5383 */
5384 public static <T extends CalculusFieldElement<T>> T scalb(final T d, final int n) {
5385 return d.scalb(n);
5386 }
5387
5388 /**
5389 * Compute least significant bit (Unit in Last Position) for a number.
5390 * @param x number from which ulp is requested
5391 * @param <T> the type of the field element
5392 * @return ulp(x)
5393 * @since 2.0
5394 */
5395 public static <T extends CalculusFieldElement<T>> T ulp(final T x) {
5396 if (Double.isInfinite(x.getReal())) {
5397 return x.newInstance(Double.POSITIVE_INFINITY);
5398 }
5399 return x.ulp();
5400 }
5401
5402 /** Get the largest whole number smaller than x.
5403 * @param x number from which floor is requested
5404 * @param <T> the type of the field element
5405 * @return a double number f such that f is an integer f <= x < f + 1.0
5406 * @since 1.3
5407 */
5408 public static <T extends CalculusFieldElement<T>> T floor(final T x) {
5409 return x.floor();
5410 }
5411
5412 /** Get the smallest whole number larger than x.
5413 * @param x number from which ceil is requested
5414 * @param <T> the type of the field element
5415 * @return a double number c such that c is an integer c - 1.0 < x <= c
5416 * @since 1.3
5417 */
5418 public static <T extends CalculusFieldElement<T>> T ceil(final T x) {
5419 return x.ceil();
5420 }
5421
5422 /** Get the whole number that is the nearest to x, or the even one if x is exactly half way between two integers.
5423 * @param x number from which nearest whole number is requested
5424 * @param <T> the type of the field element
5425 * @return a double number r such that r is an integer r - 0.5 <= x <= r + 0.5
5426 * @since 1.3
5427 */
5428 public static <T extends CalculusFieldElement<T>> T rint(final T x) {
5429 return x.rint();
5430 }
5431
5432 /** Get the closest long to x.
5433 * @param x number from which closest long is requested
5434 * @param <T> the type of the field element
5435 * @return closest long to x
5436 * @since 1.3
5437 */
5438 public static <T extends CalculusFieldElement<T>> long round(final T x) {
5439 return x.round();
5440 }
5441
5442 /** Compute the minimum of two values
5443 * @param a first value
5444 * @param b second value
5445 * @param <T> the type of the field element
5446 * @return a if a is lesser or equal to b, b otherwise
5447 * @since 1.3
5448 */
5449 public static <T extends CalculusFieldElement<T>> T min(final T a, final T b) {
5450 final double aR = a.getReal();
5451 final double bR = b.getReal();
5452 if (aR < bR) {
5453 return a;
5454 } else if (bR < aR) {
5455 return b;
5456 } else {
5457 // either the numbers are equal, or one of them is a NaN
5458 return Double.isNaN(aR) ? a : b;
5459 }
5460 }
5461
5462 /** Compute the minimum of two values
5463 * @param a first value
5464 * @param b second value
5465 * @param <T> the type of the field element
5466 * @return a if a is lesser or equal to b, b otherwise
5467 * @since 1.3
5468 */
5469 public static <T extends CalculusFieldElement<T>> T min(final T a, final double b) {
5470 final double aR = a.getReal();
5471 if (aR < b) {
5472 return a;
5473 } else if (b < aR) {
5474 return a.getField().getZero().add(b);
5475 } else {
5476 // either the numbers are equal, or one of them is a NaN
5477 return Double.isNaN(aR) ? a : a.getField().getZero().add(b);
5478 }
5479 }
5480
5481 /** Compute the maximum of two values
5482 * @param a first value
5483 * @param b second value
5484 * @param <T> the type of the field element
5485 * @return b if a is lesser or equal to b, a otherwise
5486 * @since 1.3
5487 */
5488 public static <T extends CalculusFieldElement<T>> T max(final T a, final T b) {
5489 final double aR = a.getReal();
5490 final double bR = b.getReal();
5491 if (aR < bR) {
5492 return b;
5493 } else if (bR < aR) {
5494 return a;
5495 } else {
5496 // either the numbers are equal, or one of them is a NaN
5497 return Double.isNaN(aR) ? a : b;
5498 }
5499 }
5500
5501 /** Compute the maximum of two values
5502 * @param a first value
5503 * @param b second value
5504 * @param <T> the type of the field element
5505 * @return b if a is lesser or equal to b, a otherwise
5506 * @since 1.3
5507 */
5508 public static <T extends CalculusFieldElement<T>> T max(final T a, final double b) {
5509 final double aR = a.getReal();
5510 if (aR < b) {
5511 return a.getField().getZero().add(b);
5512 } else if (b < aR) {
5513 return a;
5514 } else {
5515 // either the numbers are equal, or one of them is a NaN
5516 return Double.isNaN(aR) ? a : a.getField().getZero().add(b);
5517 }
5518 }
5519
5520 /**
5521 * Returns the hypotenuse of a triangle with sides {@code x} and {@code y}
5522 * - sqrt(<i>x</i><sup>2</sup> +<i>y</i><sup>2</sup>)<br>
5523 * avoiding intermediate overflow or underflow.
5524 *
5525 * <ul>
5526 * <li> If either argument is infinite, then the result is positive infinity.</li>
5527 * <li> else, if either argument is NaN then the result is NaN.</li>
5528 * </ul>
5529 *
5530 * @param x a value
5531 * @param y a value
5532 * @param <T> the type of the field element
5533 * @return sqrt(<i>x</i><sup>2</sup> +<i>y</i><sup>2</sup>)
5534 * @since 1.3
5535 */
5536 public static <T extends CalculusFieldElement<T>> T hypot(final T x, final T y) {
5537 return x.hypot(y);
5538 }
5539
5540 /**
5541 * Computes the remainder as prescribed by the IEEE 754 standard.
5542 * <p>
5543 * The remainder value is mathematically equal to {@code x - y*n}
5544 * where {@code n} is the mathematical integer closest to the exact mathematical value
5545 * of the quotient {@code x/y}.
5546 * If two mathematical integers are equally close to {@code x/y} then
5547 * {@code n} is the integer that is even.
5548 * </p>
5549 * <ul>
5550 * <li>If either operand is NaN, the result is NaN.</li>
5551 * <li>If the result is not NaN, the sign of the result equals the sign of the dividend.</li>
5552 * <li>If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN.</li>
5553 * <li>If the dividend is finite and the divisor is an infinity, the result equals the dividend.</li>
5554 * <li>If the dividend is a zero and the divisor is finite, the result equals the dividend.</li>
5555 * </ul>
5556 * @param dividend the number to be divided
5557 * @param divisor the number by which to divide
5558 * @param <T> the type of the field element
5559 * @return the remainder, rounded
5560 * @since 1.3
5561 */
5562 public static <T extends CalculusFieldElement<T>> T IEEEremainder(final T dividend, final double divisor) {
5563 return dividend.remainder(divisor);
5564 }
5565
5566 /**
5567 * Computes the remainder as prescribed by the IEEE 754 standard.
5568 * <p>
5569 * The remainder value is mathematically equal to {@code x - y*n}
5570 * where {@code n} is the mathematical integer closest to the exact mathematical value
5571 * of the quotient {@code x/y}.
5572 * If two mathematical integers are equally close to {@code x/y} then
5573 * {@code n} is the integer that is even.
5574 * </p>
5575 * <ul>
5576 * <li>If either operand is NaN, the result is NaN.</li>
5577 * <li>If the result is not NaN, the sign of the result equals the sign of the dividend.</li>
5578 * <li>If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN.</li>
5579 * <li>If the dividend is finite and the divisor is an infinity, the result equals the dividend.</li>
5580 * <li>If the dividend is a zero and the divisor is finite, the result equals the dividend.</li>
5581 * </ul>
5582 * @param dividend the number to be divided
5583 * @param divisor the number by which to divide
5584 * @param <T> the type of the field element
5585 * @return the remainder, rounded
5586 * @since 1.3
5587 */
5588 public static <T extends CalculusFieldElement<T>> T IEEEremainder(final T dividend, final T divisor) {
5589 return dividend.remainder(divisor);
5590 }
5591
5592 /**
5593 * Returns the first argument with the sign of the second argument.
5594 * A NaN {@code sign} argument is treated as positive.
5595 *
5596 * @param magnitude the value to return
5597 * @param sign the sign for the returned value
5598 * @param <T> the type of the field element
5599 * @return the magnitude with the same sign as the {@code sign} argument
5600 * @since 1.3
5601 */
5602 public static <T extends CalculusFieldElement<T>> T copySign(T magnitude, T sign) {
5603 return magnitude.copySign(sign);
5604 }
5605
5606 /**
5607 * Returns the first argument with the sign of the second argument.
5608 * A NaN {@code sign} argument is treated as positive.
5609 *
5610 * @param magnitude the value to return
5611 * @param sign the sign for the returned value
5612 * @param <T> the type of the field element
5613 * @return the magnitude with the same sign as the {@code sign} argument
5614 * @since 1.3
5615 */
5616 public static <T extends CalculusFieldElement<T>> T copySign(T magnitude, double sign) {
5617 return magnitude.copySign(sign);
5618 }
5619
5620 // /**
5621 // * Print out contents of arrays, and check the length.
5622 // * <p>used to generate the preset arrays originally.</p>
5623 // * @param a unused
5624 // */
5625 // public static void main(String[] a) {
5626 // FastMathCalc.printarray(System.out, "EXP_INT_TABLE_A", EXP_INT_TABLE_LEN, ExpIntTable.EXP_INT_TABLE_A);
5627 // FastMathCalc.printarray(System.out, "EXP_INT_TABLE_B", EXP_INT_TABLE_LEN, ExpIntTable.EXP_INT_TABLE_B);
5628 // FastMathCalc.printarray(System.out, "EXP_FRAC_TABLE_A", EXP_FRAC_TABLE_LEN, ExpFracTable.EXP_FRAC_TABLE_A);
5629 // FastMathCalc.printarray(System.out, "EXP_FRAC_TABLE_B", EXP_FRAC_TABLE_LEN, ExpFracTable.EXP_FRAC_TABLE_B);
5630 // FastMathCalc.printarray(System.out, "LN_MANT",LN_MANT_LEN, lnMant.LN_MANT);
5631 // FastMathCalc.printarray(System.out, "SINE_TABLE_A", SINE_TABLE_LEN, SINE_TABLE_A);
5632 // FastMathCalc.printarray(System.out, "SINE_TABLE_B", SINE_TABLE_LEN, SINE_TABLE_B);
5633 // FastMathCalc.printarray(System.out, "COSINE_TABLE_A", SINE_TABLE_LEN, COSINE_TABLE_A);
5634 // FastMathCalc.printarray(System.out, "COSINE_TABLE_B", SINE_TABLE_LEN, COSINE_TABLE_B);
5635 // FastMathCalc.printarray(System.out, "TANGENT_TABLE_A", SINE_TABLE_LEN, TANGENT_TABLE_A);
5636 // FastMathCalc.printarray(System.out, "TANGENT_TABLE_B", SINE_TABLE_LEN, TANGENT_TABLE_B);
5637 // }
5638
5639 /** Enclose large data table in nested static class so it's only loaded on first access. */
5640 private static class ExpIntTable {
5641 /** Exponential evaluated at integer values,
5642 * exp(x) = expIntTableA[x + EXP_INT_TABLE_MAX_INDEX] + expIntTableB[x+EXP_INT_TABLE_MAX_INDEX].
5643 */
5644 private static final double[] EXP_INT_TABLE_A;
5645 /** Exponential evaluated at integer values,
5646 * exp(x) = expIntTableA[x + EXP_INT_TABLE_MAX_INDEX] + expIntTableB[x+EXP_INT_TABLE_MAX_INDEX]
5647 */
5648 private static final double[] EXP_INT_TABLE_B;
5649
5650 static {
5651 if (RECOMPUTE_TABLES_AT_RUNTIME) {
5652 EXP_INT_TABLE_A = new double[EXP_INT_TABLE_LEN];
5653 EXP_INT_TABLE_B = new double[EXP_INT_TABLE_LEN];
5654
5655 final double[] tmp = new double[2];
5656 final double[] recip = new double[2];
5657
5658 // Populate expIntTable
5659 for (int i = 0; i < EXP_INT_TABLE_MAX_INDEX; i++) {
5660 FastMathCalc.expint(i, tmp);
5661 EXP_INT_TABLE_A[i + EXP_INT_TABLE_MAX_INDEX] = tmp[0];
5662 EXP_INT_TABLE_B[i + EXP_INT_TABLE_MAX_INDEX] = tmp[1];
5663
5664 if (i != 0) {
5665 // Negative integer powers
5666 FastMathCalc.splitReciprocal(tmp, recip);
5667 EXP_INT_TABLE_A[EXP_INT_TABLE_MAX_INDEX - i] = recip[0];
5668 EXP_INT_TABLE_B[EXP_INT_TABLE_MAX_INDEX - i] = recip[1];
5669 }
5670 }
5671 } else {
5672 EXP_INT_TABLE_A = FastMathLiteralArrays.loadExpIntA();
5673 EXP_INT_TABLE_B = FastMathLiteralArrays.loadExpIntB();
5674 }
5675 }
5676 }
5677
5678 /** Enclose large data table in nested static class so it's only loaded on first access. */
5679 private static class ExpFracTable {
5680 /** Exponential over the range of 0 - 1 in increments of 2^-10
5681 * exp(x/1024) = expFracTableA[x] + expFracTableB[x].
5682 * 1024 = 2^10
5683 */
5684 private static final double[] EXP_FRAC_TABLE_A;
5685 /** Exponential over the range of 0 - 1 in increments of 2^-10
5686 * exp(x/1024) = expFracTableA[x] + expFracTableB[x].
5687 */
5688 private static final double[] EXP_FRAC_TABLE_B;
5689
5690 static {
5691 if (RECOMPUTE_TABLES_AT_RUNTIME) {
5692 EXP_FRAC_TABLE_A = new double[EXP_FRAC_TABLE_LEN];
5693 EXP_FRAC_TABLE_B = new double[EXP_FRAC_TABLE_LEN];
5694
5695 final double[] tmp = new double[2];
5696
5697 // Populate expFracTable
5698 final double factor = 1d / (EXP_FRAC_TABLE_LEN - 1);
5699 for (int i = 0; i < EXP_FRAC_TABLE_A.length; i++) {
5700 FastMathCalc.slowexp(i * factor, tmp);
5701 EXP_FRAC_TABLE_A[i] = tmp[0];
5702 EXP_FRAC_TABLE_B[i] = tmp[1];
5703 }
5704 } else {
5705 EXP_FRAC_TABLE_A = FastMathLiteralArrays.loadExpFracA();
5706 EXP_FRAC_TABLE_B = FastMathLiteralArrays.loadExpFracB();
5707 }
5708 }
5709 }
5710
5711 /** Enclose large data table in nested static class so it's only loaded on first access. */
5712 private static class lnMant {
5713 /** Extended precision logarithm table over the range 1 - 2 in increments of 2^-10. */
5714 private static final double[][] LN_MANT;
5715
5716 static {
5717 if (RECOMPUTE_TABLES_AT_RUNTIME) {
5718 LN_MANT = new double[LN_MANT_LEN][];
5719
5720 // Populate lnMant table
5721 for (int i = 0; i < LN_MANT.length; i++) {
5722 final double d = Double.longBitsToDouble( (((long) i) << 42) | 0x3ff0000000000000L );
5723 LN_MANT[i] = FastMathCalc.slowLog(d);
5724 }
5725 } else {
5726 LN_MANT = FastMathLiteralArrays.loadLnMant();
5727 }
5728 }
5729 }
5730
5731 /** Enclose the Cody/Waite reduction (used in "sin", "cos" and "tan"). */
5732 private static class CodyWaite {
5733 /** k */
5734 private final int finalK;
5735 /** remA */
5736 private final double finalRemA;
5737 /** remB */
5738 private final double finalRemB;
5739
5740 /**
5741 * @param xa Argument.
5742 */
5743 CodyWaite(double xa) {
5744 // Estimate k.
5745 //k = (int)(xa / 1.5707963267948966);
5746 int k = (int)(xa * 0.6366197723675814);
5747
5748 // Compute remainder.
5749 double remA;
5750 double remB;
5751 while (true) {
5752 double a = -k * 1.570796251296997;
5753 remA = xa + a;
5754 remB = -(remA - xa - a);
5755
5756 a = -k * 7.549789948768648E-8;
5757 double b = remA;
5758 remA = a + b;
5759 remB += -(remA - b - a);
5760
5761 a = -k * 6.123233995736766E-17;
5762 b = remA;
5763 remA = a + b;
5764 remB += -(remA - b - a);
5765
5766 if (remA > 0) {
5767 break;
5768 }
5769
5770 // Remainder is negative, so decrement k and try again.
5771 // This should only happen if the input is very close
5772 // to an even multiple of pi/2.
5773 --k;
5774 }
5775
5776 this.finalK = k;
5777 this.finalRemA = remA;
5778 this.finalRemB = remB;
5779 }
5780
5781 /**
5782 * @return k
5783 */
5784 int getK() {
5785 return finalK;
5786 }
5787 /**
5788 * @return remA
5789 */
5790 double getRemA() {
5791 return finalRemA;
5792 }
5793 /**
5794 * @return remB
5795 */
5796 double getRemB() {
5797 return finalRemB;
5798 }
5799 }
5800
5801 }