-
Notifications
You must be signed in to change notification settings - Fork 355
/
FastMath.java
4340 lines (3676 loc) · 137 KB
/
FastMath.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math4.util;
import java.io.PrintStream;
import org.apache.commons.numbers.core.Precision;
import org.apache.commons.math4.exception.MathArithmeticException;
import org.apache.commons.math4.exception.util.LocalizedFormats;
/**
* Faster, more accurate, portable alternative to {@link Math} and
* {@link StrictMath} for large scale computation.
* <p>
* FastMath is a drop-in replacement for both Math and StrictMath. This
* means that for any method in Math (say {@code Math.sin(x)} or
* {@code Math.cbrt(y)}), user can directly change the class and use the
* methods as is (using {@code FastMath.sin(x)} or {@code FastMath.cbrt(y)}
* in the previous example).
* </p>
* <p>
* FastMath speed is achieved by relying heavily on optimizing compilers
* to native code present in many JVMs today and use of large tables.
* The larger tables are lazily initialized on first use, so that the setup
* time does not penalize methods that don't need them.
* </p>
* <p>
* Note that FastMath is
* extensively used inside Apache Commons Math, so by calling some algorithms,
* the overhead when the tables need to be initialized will occur
* regardless of the end-user calling FastMath methods directly or not.
* Performance figures for a specific JVM and hardware can be evaluated by
* running the FastMathTestPerformance tests in the test directory of the source
* distribution.
* </p>
* <p>
* FastMath accuracy should be mostly independent of the JVM as it relies only
* on IEEE-754 basic operations and on embedded tables. Almost all operations
* are accurate to about 0.5 ulp throughout the domain range. This statement,
* of course is only a rough global observed behavior, it is <em>not</em> a
* guarantee for <em>every</em> double numbers input (see William Kahan's <a
* href="http://en.wikipedia.org/wiki/Rounding#The_table-maker.27s_dilemma">Table
* Maker's Dilemma</a>).
* </p>
* <p>
* FastMath additionally implements the following methods not found in Math/StrictMath:
* <ul>
* <li>{@link #asinh(double)}</li>
* <li>{@link #acosh(double)}</li>
* <li>{@link #atanh(double)}</li>
* </ul>
* The following methods are found in Math/StrictMath since 1.6 only, they are provided
* by FastMath even in 1.5 Java virtual machines
* <ul>
* <li>{@link #copySign(double, double)}</li>
* <li>{@link #getExponent(double)}</li>
* <li>{@link #nextAfter(double,double)}</li>
* <li>{@link #nextUp(double)}</li>
* <li>{@link #scalb(double, int)}</li>
* <li>{@link #copySign(float, float)}</li>
* <li>{@link #getExponent(float)}</li>
* <li>{@link #nextAfter(float,double)}</li>
* <li>{@link #nextUp(float)}</li>
* <li>{@link #scalb(float, int)}</li>
* </ul>
* @since 2.2
*/
public class FastMath {
/** Archimede's constant PI, ratio of circle circumference to diameter. */
public static final double PI = 105414357.0 / 33554432.0 + 1.984187159361080883e-9;
/** Napier's constant e, base of the natural logarithm. */
public static final double E = 2850325.0 / 1048576.0 + 8.254840070411028747e-8;
/** Index of exp(0) in the array of integer exponentials. */
static final int EXP_INT_TABLE_MAX_INDEX = 750;
/** Length of the array of integer exponentials. */
static final int EXP_INT_TABLE_LEN = EXP_INT_TABLE_MAX_INDEX * 2;
/** Logarithm table length. */
static final int LN_MANT_LEN = 1024;
/** Exponential fractions table length. */
static final int EXP_FRAC_TABLE_LEN = 1025; // 0, 1/1024, ... 1024/1024
/** StrictMath.log(Double.MAX_VALUE): {@value} */
private static final double LOG_MAX_VALUE = StrictMath.log(Double.MAX_VALUE);
/** Indicator for tables initialization.
* <p>
* This compile-time constant should be set to true only if one explicitly
* wants to compute the tables at class loading time instead of using the
* already computed ones provided as literal arrays below.
* </p>
*/
private static final boolean RECOMPUTE_TABLES_AT_RUNTIME = false;
/** log(2) (high bits). */
private static final double LN_2_A = 0.693147063255310059;
/** log(2) (low bits). */
private static final double LN_2_B = 1.17304635250823482e-7;
/** Coefficients for log, when input 0.99 < x < 1.01. */
private static final double LN_QUICK_COEF[][] = {
{1.0, 5.669184079525E-24},
{-0.25, -0.25},
{0.3333333134651184, 1.986821492305628E-8},
{-0.25, -6.663542893624021E-14},
{0.19999998807907104, 1.1921056801463227E-8},
{-0.1666666567325592, -7.800414592973399E-9},
{0.1428571343421936, 5.650007086920087E-9},
{-0.12502530217170715, -7.44321345601866E-11},
{0.11113807559013367, 9.219544613762692E-9},
};
/** Coefficients for log in the range of 1.0 < x < 1.0 + 2^-10. */
private static final double LN_HI_PREC_COEF[][] = {
{1.0, -6.032174644509064E-23},
{-0.25, -0.25},
{0.3333333134651184, 1.9868161777724352E-8},
{-0.2499999701976776, -2.957007209750105E-8},
{0.19999954104423523, 1.5830993332061267E-10},
{-0.16624879837036133, -2.6033824355191673E-8}
};
/** Sine, Cosine, Tangent tables are for 0, 1/8, 2/8, ... 13/8 = PI/2 approx. */
private static final int SINE_TABLE_LEN = 14;
/** Sine table (high bits). */
private static final double SINE_TABLE_A[] =
{
+0.0d,
+0.1246747374534607d,
+0.24740394949913025d,
+0.366272509098053d,
+0.4794255495071411d,
+0.5850973129272461d,
+0.6816387176513672d,
+0.7675435543060303d,
+0.8414709568023682d,
+0.902267575263977d,
+0.9489846229553223d,
+0.9808930158615112d,
+0.9974949359893799d,
+0.9985313415527344d,
};
/** Sine table (low bits). */
private static final double SINE_TABLE_B[] =
{
+0.0d,
-4.068233003401932E-9d,
+9.755392680573412E-9d,
+1.9987994582857286E-8d,
-1.0902938113007961E-8d,
-3.9986783938944604E-8d,
+4.23719669792332E-8d,
-5.207000323380292E-8d,
+2.800552834259E-8d,
+1.883511811213715E-8d,
-3.5997360512765566E-9d,
+4.116164446561962E-8d,
+5.0614674548127384E-8d,
-1.0129027912496858E-9d,
};
/** Cosine table (high bits). */
private static final double COSINE_TABLE_A[] =
{
+1.0d,
+0.9921976327896118d,
+0.9689123630523682d,
+0.9305076599121094d,
+0.8775825500488281d,
+0.8109631538391113d,
+0.7316888570785522d,
+0.6409968137741089d,
+0.5403022766113281d,
+0.4311765432357788d,
+0.3153223395347595d,
+0.19454771280288696d,
+0.07073719799518585d,
-0.05417713522911072d,
};
/** Cosine table (low bits). */
private static final double COSINE_TABLE_B[] =
{
+0.0d,
+3.4439717236742845E-8d,
+5.865827662008209E-8d,
-3.7999795083850525E-8d,
+1.184154459111628E-8d,
-3.43338934259355E-8d,
+1.1795268640216787E-8d,
+4.438921624363781E-8d,
+2.925681159240093E-8d,
-2.6437112632041807E-8d,
+2.2860509143963117E-8d,
-4.813899778443457E-9d,
+3.6725170580355583E-9d,
+2.0217439756338078E-10d,
};
/** Tangent table, used by atan() (high bits). */
private static final double TANGENT_TABLE_A[] =
{
+0.0d,
+0.1256551444530487d,
+0.25534194707870483d,
+0.3936265707015991d,
+0.5463024377822876d,
+0.7214844226837158d,
+0.9315965175628662d,
+1.1974215507507324d,
+1.5574076175689697d,
+2.092571258544922d,
+3.0095696449279785d,
+5.041914939880371d,
+14.101419448852539d,
-18.430862426757812d,
};
/** Tangent table, used by atan() (low bits). */
private static final double TANGENT_TABLE_B[] =
{
+0.0d,
-7.877917738262007E-9d,
-2.5857668567479893E-8d,
+5.2240336371356666E-9d,
+5.206150291559893E-8d,
+1.8307188599677033E-8d,
-5.7618793749770706E-8d,
+7.848361555046424E-8d,
+1.0708593250394448E-7d,
+1.7827257129423813E-8d,
+2.893485277253286E-8d,
+3.1660099222737955E-7d,
+4.983191803254889E-7d,
-3.356118100840571E-7d,
};
/** Bits of 1/(2*pi), need for reducePayneHanek(). */
private static final long RECIP_2PI[] = new long[] {
(0x28be60dbL << 32) | 0x9391054aL,
(0x7f09d5f4L << 32) | 0x7d4d3770L,
(0x36d8a566L << 32) | 0x4f10e410L,
(0x7f9458eaL << 32) | 0xf7aef158L,
(0x6dc91b8eL << 32) | 0x909374b8L,
(0x01924bbaL << 32) | 0x82746487L,
(0x3f877ac7L << 32) | 0x2c4a69cfL,
(0xba208d7dL << 32) | 0x4baed121L,
(0x3a671c09L << 32) | 0xad17df90L,
(0x4e64758eL << 32) | 0x60d4ce7dL,
(0x272117e2L << 32) | 0xef7e4a0eL,
(0xc7fe25ffL << 32) | 0xf7816603L,
(0xfbcbc462L << 32) | 0xd6829b47L,
(0xdb4d9fb3L << 32) | 0xc9f2c26dL,
(0xd3d18fd9L << 32) | 0xa797fa8bL,
(0x5d49eeb1L << 32) | 0xfaf97c5eL,
(0xcf41ce7dL << 32) | 0xe294a4baL,
0x9afed7ecL << 32 };
/** Bits of pi/4, need for reducePayneHanek(). */
private static final long PI_O_4_BITS[] = new long[] {
(0xc90fdaa2L << 32) | 0x2168c234L,
(0xc4c6628bL << 32) | 0x80dc1cd1L };
/** Eighths.
* This is used by sinQ, because its faster to do a table lookup than
* a multiply in this time-critical routine
*/
private static final double EIGHTHS[] = {0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0, 1.125, 1.25, 1.375, 1.5, 1.625};
/** Table of 2^((n+2)/3) */
private static final double CBRTTWO[] = { 0.6299605249474366,
0.7937005259840998,
1.0,
1.2599210498948732,
1.5874010519681994 };
/*
* There are 52 bits in the mantissa of a double.
* For additional precision, the code splits double numbers into two parts,
* by clearing the low order 30 bits if possible, and then performs the arithmetic
* on each half separately.
*/
/**
* 0x40000000 - used to split a double into two parts, both with the low order bits cleared.
* Equivalent to 2^30.
*/
private static final long HEX_40000000 = 0x40000000L; // 1073741824L
/** Mask used to clear low order 30 bits */
private static final long MASK_30BITS = -1L - (HEX_40000000 -1); // 0xFFFFFFFFC0000000L;
/** Mask used to clear the non-sign part of an int. */
private static final int MASK_NON_SIGN_INT = 0x7fffffff;
/** Mask used to clear the non-sign part of a long. */
private static final long MASK_NON_SIGN_LONG = 0x7fffffffffffffffl;
/** Mask used to extract exponent from double bits. */
private static final long MASK_DOUBLE_EXPONENT = 0x7ff0000000000000L;
/** Mask used to extract mantissa from double bits. */
private static final long MASK_DOUBLE_MANTISSA = 0x000fffffffffffffL;
/** Mask used to add implicit high order bit for normalized double. */
private static final long IMPLICIT_HIGH_BIT = 0x0010000000000000L;
/** 2^52 - double numbers this large must be integral (no fraction) or NaN or Infinite */
private static final double TWO_POWER_52 = 4503599627370496.0;
/** Constant: {@value}. */
private static final double F_1_3 = 1d / 3d;
/** Constant: {@value}. */
private static final double F_1_5 = 1d / 5d;
/** Constant: {@value}. */
private static final double F_1_7 = 1d / 7d;
/** Constant: {@value}. */
private static final double F_1_9 = 1d / 9d;
/** Constant: {@value}. */
private static final double F_1_11 = 1d / 11d;
/** Constant: {@value}. */
private static final double F_1_13 = 1d / 13d;
/** Constant: {@value}. */
private static final double F_1_15 = 1d / 15d;
/** Constant: {@value}. */
private static final double F_1_17 = 1d / 17d;
/** Constant: {@value}. */
private static final double F_3_4 = 3d / 4d;
/** Constant: {@value}. */
private static final double F_15_16 = 15d / 16d;
/** Constant: {@value}. */
private static final double F_13_14 = 13d / 14d;
/** Constant: {@value}. */
private static final double F_11_12 = 11d / 12d;
/** Constant: {@value}. */
private static final double F_9_10 = 9d / 10d;
/** Constant: {@value}. */
private static final double F_7_8 = 7d / 8d;
/** Constant: {@value}. */
private static final double F_5_6 = 5d / 6d;
/** Constant: {@value}. */
private static final double F_1_2 = 1d / 2d;
/** Constant: {@value}. */
private static final double F_1_4 = 1d / 4d;
/**
* Private Constructor
*/
private FastMath() {}
// Generic helper methods
/**
* Get the high order bits from the mantissa.
* Equivalent to adding and subtracting HEX_40000 but also works for very large numbers
*
* @param d the value to split
* @return the high order part of the mantissa
*/
private static double doubleHighPart(double d) {
if (d > -Precision.SAFE_MIN && d < Precision.SAFE_MIN){
return d; // These are un-normalised - don't try to convert
}
long xl = Double.doubleToRawLongBits(d); // can take raw bits because just gonna convert it back
xl &= MASK_30BITS; // Drop low order bits
return Double.longBitsToDouble(xl);
}
/** Compute the square root of a number.
* <p><b>Note:</b> this implementation currently delegates to {@link Math#sqrt}
* @param a number on which evaluation is done
* @return square root of a
*/
public static double sqrt(final double a) {
return Math.sqrt(a);
}
/** Compute the hyperbolic cosine of a number.
* @param x number on which evaluation is done
* @return hyperbolic cosine of x
*/
public static double cosh(double x) {
if (Double.isNaN(x)) {
return x;
}
// cosh[z] = (exp(z) + exp(-z))/2
// for numbers with magnitude 20 or so,
// exp(-z) can be ignored in comparison with exp(z)
if (x > 20) {
if (x >= LOG_MAX_VALUE) {
// Avoid overflow (MATH-905).
final double t = exp(0.5 * x);
return (0.5 * t) * t;
} else {
return 0.5 * exp(x);
}
} else if (x < -20) {
if (x <= -LOG_MAX_VALUE) {
// Avoid overflow (MATH-905).
final double t = exp(-0.5 * x);
return (0.5 * t) * t;
} else {
return 0.5 * exp(-x);
}
}
final double hiPrec[] = new double[2];
if (x < 0.0) {
x = -x;
}
exp(x, 0.0, hiPrec);
double ya = hiPrec[0] + hiPrec[1];
double yb = -(ya - hiPrec[0] - hiPrec[1]);
double temp = ya * HEX_40000000;
double yaa = ya + temp - temp;
double yab = ya - yaa;
// recip = 1/y
double recip = 1.0/ya;
temp = recip * HEX_40000000;
double recipa = recip + temp - temp;
double recipb = recip - recipa;
// Correct for rounding in division
recipb += (1.0 - yaa*recipa - yaa*recipb - yab*recipa - yab*recipb) * recip;
// Account for yb
recipb += -yb * recip * recip;
// y = y + 1/y
temp = ya + recipa;
yb += -(temp - ya - recipa);
ya = temp;
temp = ya + recipb;
yb += -(temp - ya - recipb);
ya = temp;
double result = ya + yb;
result *= 0.5;
return result;
}
/** Compute the hyperbolic sine of a number.
* @param x number on which evaluation is done
* @return hyperbolic sine of x
*/
public static double sinh(double x) {
boolean negate = false;
if (Double.isNaN(x)) {
return x;
}
// sinh[z] = (exp(z) - exp(-z) / 2
// for values of z larger than about 20,
// exp(-z) can be ignored in comparison with exp(z)
if (x > 20) {
if (x >= LOG_MAX_VALUE) {
// Avoid overflow (MATH-905).
final double t = exp(0.5 * x);
return (0.5 * t) * t;
} else {
return 0.5 * exp(x);
}
} else if (x < -20) {
if (x <= -LOG_MAX_VALUE) {
// Avoid overflow (MATH-905).
final double t = exp(-0.5 * x);
return (-0.5 * t) * t;
} else {
return -0.5 * exp(-x);
}
}
if (x == 0) {
return x;
}
if (x < 0.0) {
x = -x;
negate = true;
}
double result;
if (x > 0.25) {
double hiPrec[] = new double[2];
exp(x, 0.0, hiPrec);
double ya = hiPrec[0] + hiPrec[1];
double yb = -(ya - hiPrec[0] - hiPrec[1]);
double temp = ya * HEX_40000000;
double yaa = ya + temp - temp;
double yab = ya - yaa;
// recip = 1/y
double recip = 1.0/ya;
temp = recip * HEX_40000000;
double recipa = recip + temp - temp;
double recipb = recip - recipa;
// Correct for rounding in division
recipb += (1.0 - yaa*recipa - yaa*recipb - yab*recipa - yab*recipb) * recip;
// Account for yb
recipb += -yb * recip * recip;
recipa = -recipa;
recipb = -recipb;
// y = y + 1/y
temp = ya + recipa;
yb += -(temp - ya - recipa);
ya = temp;
temp = ya + recipb;
yb += -(temp - ya - recipb);
ya = temp;
result = ya + yb;
result *= 0.5;
}
else {
double hiPrec[] = new double[2];
expm1(x, hiPrec);
double ya = hiPrec[0] + hiPrec[1];
double yb = -(ya - hiPrec[0] - hiPrec[1]);
/* Compute expm1(-x) = -expm1(x) / (expm1(x) + 1) */
double denom = 1.0 + ya;
double denomr = 1.0 / denom;
double denomb = -(denom - 1.0 - ya) + yb;
double ratio = ya * denomr;
double temp = ratio * HEX_40000000;
double ra = ratio + temp - temp;
double rb = ratio - ra;
temp = denom * HEX_40000000;
double za = denom + temp - temp;
double zb = denom - za;
rb += (ya - za*ra - za*rb - zb*ra - zb*rb) * denomr;
// Adjust for yb
rb += yb*denomr; // numerator
rb += -ya * denomb * denomr * denomr; // denominator
// y = y - 1/y
temp = ya + ra;
yb += -(temp - ya - ra);
ya = temp;
temp = ya + rb;
yb += -(temp - ya - rb);
ya = temp;
result = ya + yb;
result *= 0.5;
}
if (negate) {
result = -result;
}
return result;
}
/** Compute the hyperbolic tangent of a number.
* @param x number on which evaluation is done
* @return hyperbolic tangent of x
*/
public static double tanh(double x) {
boolean negate = false;
if (Double.isNaN(x)) {
return x;
}
// tanh[z] = sinh[z] / cosh[z]
// = (exp(z) - exp(-z)) / (exp(z) + exp(-z))
// = (exp(2x) - 1) / (exp(2x) + 1)
// for magnitude > 20, sinh[z] == cosh[z] in double precision
if (x > 20.0) {
return 1.0;
}
if (x < -20) {
return -1.0;
}
if (x == 0) {
return x;
}
if (x < 0.0) {
x = -x;
negate = true;
}
double result;
if (x >= 0.5) {
double hiPrec[] = new double[2];
// tanh(x) = (exp(2x) - 1) / (exp(2x) + 1)
exp(x*2.0, 0.0, hiPrec);
double ya = hiPrec[0] + hiPrec[1];
double yb = -(ya - hiPrec[0] - hiPrec[1]);
/* Numerator */
double na = -1.0 + ya;
double nb = -(na + 1.0 - ya);
double temp = na + yb;
nb += -(temp - na - yb);
na = temp;
/* Denominator */
double da = 1.0 + ya;
double db = -(da - 1.0 - ya);
temp = da + yb;
db += -(temp - da - yb);
da = temp;
temp = da * HEX_40000000;
double daa = da + temp - temp;
double dab = da - daa;
// ratio = na/da
double ratio = na/da;
temp = ratio * HEX_40000000;
double ratioa = ratio + temp - temp;
double ratiob = ratio - ratioa;
// Correct for rounding in division
ratiob += (na - daa*ratioa - daa*ratiob - dab*ratioa - dab*ratiob) / da;
// Account for nb
ratiob += nb / da;
// Account for db
ratiob += -db * na / da / da;
result = ratioa + ratiob;
}
else {
double hiPrec[] = new double[2];
// tanh(x) = expm1(2x) / (expm1(2x) + 2)
expm1(x*2.0, hiPrec);
double ya = hiPrec[0] + hiPrec[1];
double yb = -(ya - hiPrec[0] - hiPrec[1]);
/* Denominator */
double da = 2.0 + ya;
double db = -(da - 2.0 - ya);
double temp = da + yb;
db += -(temp - da - yb);
da = temp;
temp = da * HEX_40000000;
double daa = da + temp - temp;
double dab = da - daa;
// ratio = na/da
double ratio = ya /da;
temp = ratio * HEX_40000000;
double ratioa = ratio + temp - temp;
double ratiob = ratio - ratioa;
// Correct for rounding in division
ratiob += (ya - daa*ratioa - daa*ratiob - dab*ratioa - dab*ratiob) / da;
// Account for nb
ratiob += yb / da;
// Account for db
ratiob += -db * ya / da / da;
result = ratioa + ratiob;
}
if (negate) {
result = -result;
}
return result;
}
/** Compute the inverse hyperbolic cosine of a number.
* @param a number on which evaluation is done
* @return inverse hyperbolic cosine of a
*/
public static double acosh(final double a) {
return FastMath.log(a + FastMath.sqrt(a * a - 1));
}
/** Compute the inverse hyperbolic sine of a number.
* @param a number on which evaluation is done
* @return inverse hyperbolic sine of a
*/
public static double asinh(double a) {
boolean negative = false;
if (a < 0) {
negative = true;
a = -a;
}
double absAsinh;
if (a > 0.167) {
absAsinh = FastMath.log(FastMath.sqrt(a * a + 1) + a);
} else {
final double a2 = a * a;
if (a > 0.097) {
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);
} else if (a > 0.036) {
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);
} else if (a > 0.0036) {
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);
} else {
absAsinh = a * (1 - a2 * (F_1_3 - a2 * F_1_5 * F_3_4) * F_1_2);
}
}
return negative ? -absAsinh : absAsinh;
}
/** Compute the inverse hyperbolic tangent of a number.
* @param a number on which evaluation is done
* @return inverse hyperbolic tangent of a
*/
public static double atanh(double a) {
boolean negative = false;
if (a < 0) {
negative = true;
a = -a;
}
double absAtanh;
if (a > 0.15) {
absAtanh = 0.5 * FastMath.log((1 + a) / (1 - a));
} else {
final double a2 = a * a;
if (a > 0.087) {
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))))))));
} else if (a > 0.031) {
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))))));
} else if (a > 0.003) {
absAtanh = a * (1 + a2 * (F_1_3 + a2 * (F_1_5 + a2 * (F_1_7 + a2 * F_1_9))));
} else {
absAtanh = a * (1 + a2 * (F_1_3 + a2 * F_1_5));
}
}
return negative ? -absAtanh : absAtanh;
}
/** Compute the signum of a number.
* The signum is -1 for negative numbers, +1 for positive numbers and 0 otherwise
* @param a number on which evaluation is done
* @return -1.0, -0.0, +0.0, +1.0 or NaN depending on sign of a
*/
public static double signum(final double a) {
return (a < 0.0) ? -1.0 : ((a > 0.0) ? 1.0 : a); // return +0.0/-0.0/NaN depending on a
}
/** Compute the signum of a number.
* The signum is -1 for negative numbers, +1 for positive numbers and 0 otherwise
* @param a number on which evaluation is done
* @return -1.0, -0.0, +0.0, +1.0 or NaN depending on sign of a
*/
public static float signum(final float a) {
return (a < 0.0f) ? -1.0f : ((a > 0.0f) ? 1.0f : a); // return +0.0/-0.0/NaN depending on a
}
/** Compute next number towards positive infinity.
* @param a number to which neighbor should be computed
* @return neighbor of a towards positive infinity
*/
public static double nextUp(final double a) {
return nextAfter(a, Double.POSITIVE_INFINITY);
}
/** Compute next number towards positive infinity.
* @param a number to which neighbor should be computed
* @return neighbor of a towards positive infinity
*/
public static float nextUp(final float a) {
return nextAfter(a, Float.POSITIVE_INFINITY);
}
/** Compute next number towards negative infinity.
* @param a number to which neighbor should be computed
* @return neighbor of a towards negative infinity
* @since 3.4
*/
public static double nextDown(final double a) {
return nextAfter(a, Double.NEGATIVE_INFINITY);
}
/** Compute next number towards negative infinity.
* @param a number to which neighbor should be computed
* @return neighbor of a towards negative infinity
* @since 3.4
*/
public static float nextDown(final float a) {
return nextAfter(a, Float.NEGATIVE_INFINITY);
}
/** Returns a pseudo-random number between 0.0 and 1.0.
* <p><b>Note:</b> this implementation currently delegates to {@link Math#random}
* @return a random number between 0.0 and 1.0
*/
public static double random() {
return Math.random();
}
/**
* Exponential function.
*
* Computes exp(x), function result is nearly rounded. It will be correctly
* rounded to the theoretical value for 99.9% of input values, otherwise it will
* have a 1 ULP error.
*
* Method:
* Lookup intVal = exp(int(x))
* Lookup fracVal = exp(int(x-int(x) / 1024.0) * 1024.0 );
* Compute z as the exponential of the remaining bits by a polynomial minus one
* exp(x) = intVal * fracVal * (1 + z)
*
* Accuracy:
* Calculation is done with 63 bits of precision, so result should be correctly
* rounded for 99.9% of input values, with less than 1 ULP error otherwise.
*
* @param x a double
* @return double e<sup>x</sup>
*/
public static double exp(double x) {
return exp(x, 0.0, null);
}
/**
* Internal helper method for exponential function.
* @param x original argument of the exponential function
* @param extra extra bits of precision on input (To Be Confirmed)
* @param hiPrec extra bits of precision on output (To Be Confirmed)
* @return exp(x)
*/
private static double exp(double x, double extra, double[] hiPrec) {
double intPartA;
double intPartB;
int intVal = (int) x;
/* Lookup exp(floor(x)).
* intPartA will have the upper 22 bits, intPartB will have the lower
* 52 bits.
*/
if (x < 0.0) {
// We don't check against intVal here as conversion of large negative double values
// may be affected by a JIT bug. Subsequent comparisons can safely use intVal
if (x < -746d) {
if (hiPrec != null) {
hiPrec[0] = 0.0;
hiPrec[1] = 0.0;
}
return 0.0;
}
if (intVal < -709) {
/* This will produce a subnormal output */
final double result = exp(x+40.19140625, extra, hiPrec) / 285040095144011776.0;
if (hiPrec != null) {
hiPrec[0] /= 285040095144011776.0;
hiPrec[1] /= 285040095144011776.0;
}
return result;
}
if (intVal == -709) {
/* exp(1.494140625) is nearly a machine number... */
final double result = exp(x+1.494140625, extra, hiPrec) / 4.455505956692756620;
if (hiPrec != null) {
hiPrec[0] /= 4.455505956692756620;
hiPrec[1] /= 4.455505956692756620;
}
return result;
}
intVal--;
} else {
if (intVal > 709) {
if (hiPrec != null) {
hiPrec[0] = Double.POSITIVE_INFINITY;
hiPrec[1] = 0.0;
}
return Double.POSITIVE_INFINITY;
}
}
intPartA = ExpIntTable.EXP_INT_TABLE_A[EXP_INT_TABLE_MAX_INDEX+intVal];
intPartB = ExpIntTable.EXP_INT_TABLE_B[EXP_INT_TABLE_MAX_INDEX+intVal];
/* Get the fractional part of x, find the greatest multiple of 2^-10 less than
* x and look up the exp function of it.
* fracPartA will have the upper 22 bits, fracPartB the lower 52 bits.
*/
final int intFrac = (int) ((x - intVal) * 1024.0);
final double fracPartA = ExpFracTable.EXP_FRAC_TABLE_A[intFrac];
final double fracPartB = ExpFracTable.EXP_FRAC_TABLE_B[intFrac];
/* epsilon is the difference in x from the nearest multiple of 2^-10. It
* has a value in the range 0 <= epsilon < 2^-10.
* Do the subtraction from x as the last step to avoid possible loss of precision.
*/
final double epsilon = x - (intVal + intFrac / 1024.0);
/* Compute z = exp(epsilon) - 1.0 via a minimax polynomial. z has
full double precision (52 bits). Since z < 2^-10, we will have
62 bits of precision when combined with the constant 1. This will be
used in the last addition below to get proper rounding. */
/* Remez generated polynomial. Converges on the interval [0, 2^-10], error
is less than 0.5 ULP */
double z = 0.04168701738764507;
z = z * epsilon + 0.1666666505023083;
z = z * epsilon + 0.5000000000042687;
z = z * epsilon + 1.0;
z = z * epsilon + -3.940510424527919E-20;
/* Compute (intPartA+intPartB) * (fracPartA+fracPartB) by binomial
expansion.
tempA is exact since intPartA and intPartB only have 22 bits each.
tempB will have 52 bits of precision.
*/
double tempA = intPartA * fracPartA;
double tempB = intPartA * fracPartB + intPartB * fracPartA + intPartB * fracPartB;
/* Compute the result. (1+z)(tempA+tempB). Order of operations is
important. For accuracy add by increasing size. tempA is exact and
much larger than the others. If there are extra bits specified from the
pow() function, use them. */
final double tempC = tempB + tempA;
// If tempC is positive infinite, the evaluation below could result in NaN,
// because z could be negative at the same time.
if (tempC == Double.POSITIVE_INFINITY) {
return Double.POSITIVE_INFINITY;
}
final double result;
if (extra != 0.0) {
result = tempC*extra*z + tempC*extra + tempC*z + tempB + tempA;
} else {
result = tempC*z + tempB + tempA;
}
if (hiPrec != null) {
// If requesting high precision
hiPrec[0] = tempA;
hiPrec[1] = tempC*extra*z + tempC*extra + tempC*z + tempB;
}
return result;
}
/** Compute exp(x) - 1
* @param x number to compute shifted exponential
* @return exp(x) - 1
*/
public static double expm1(double x) {
return expm1(x, null);
}
/** Internal helper method for expm1
* @param x number to compute shifted exponential