-
Notifications
You must be signed in to change notification settings - Fork 668
/
Math.java
3045 lines (2868 loc) · 117 KB
/
Math.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
/*
* Copyright (c) 1994, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang;
import jdk.internal.HotSpotIntrinsicCandidate;
import jdk.internal.math.DoubleConsts;
import jdk.internal.math.FloatConsts;
import java.math.BigDecimal;
import java.util.Random;
/**
* The class {@code Math} contains methods for performing basic
* numeric operations such as the elementary exponential, logarithm,
* square root, and trigonometric functions.
*
* <p>Unlike some of the numeric methods of class
* {@code StrictMath}, all implementations of the equivalent
* functions of class {@code Math} are not defined to return the
* bit-for-bit same results. This relaxation permits
* better-performing implementations where strict reproducibility is
* not required.
*
* <p>By default many of the {@code Math} methods simply call
* the equivalent method in {@code StrictMath} for their
* implementation. Code generators are encouraged to use
* platform-specific native libraries or microprocessor instructions,
* where available, to provide higher-performance implementations of
* {@code Math} methods. Such higher-performance
* implementations still must conform to the specification for
* {@code Math}.
*
* <p>The quality of implementation specifications concern two
* properties, accuracy of the returned result and monotonicity of the
* method. Accuracy of the floating-point {@code Math} methods is
* measured in terms of <i>ulps</i>, units in the last place. For a
* given floating-point format, an {@linkplain #ulp(double) ulp} of a
* specific real number value is the distance between the two
* floating-point values bracketing that numerical value. When
* discussing the accuracy of a method as a whole rather than at a
* specific argument, the number of ulps cited is for the worst-case
* error at any argument. If a method always has an error less than
* 0.5 ulps, the method always returns the floating-point number
* nearest the exact result; such a method is <i>correctly
* rounded</i>. A correctly rounded method is generally the best a
* floating-point approximation can be; however, it is impractical for
* many floating-point methods to be correctly rounded. Instead, for
* the {@code Math} class, a larger error bound of 1 or 2 ulps is
* allowed for certain methods. Informally, with a 1 ulp error bound,
* when the exact result is a representable number, the exact result
* should be returned as the computed result; otherwise, either of the
* two floating-point values which bracket the exact result may be
* returned. For exact results large in magnitude, one of the
* endpoints of the bracket may be infinite. Besides accuracy at
* individual arguments, maintaining proper relations between the
* method at different arguments is also important. Therefore, most
* methods with more than 0.5 ulp errors are required to be
* <i>semi-monotonic</i>: whenever the mathematical function is
* non-decreasing, so is the floating-point approximation, likewise,
* whenever the mathematical function is non-increasing, so is the
* floating-point approximation. Not all approximations that have 1
* ulp accuracy will automatically meet the monotonicity requirements.
*
* <p>
* The platform uses signed two's complement integer arithmetic with
* int and long primitive types. The developer should choose
* the primitive type to ensure that arithmetic operations consistently
* produce correct results, which in some cases means the operations
* will not overflow the range of values of the computation.
* The best practice is to choose the primitive type and algorithm to avoid
* overflow. In cases where the size is {@code int} or {@code long} and
* overflow errors need to be detected, the methods {@code addExact},
* {@code subtractExact}, {@code multiplyExact}, and {@code toIntExact}
* throw an {@code ArithmeticException} when the results overflow.
* For other arithmetic operations such as divide, absolute value,
* increment by one, decrement by one, and negation, overflow occurs only with
* a specific minimum or maximum value and should be checked against
* the minimum or maximum as appropriate.
*
* @author unascribed
* @author Joseph D. Darcy
* @since 1.0
*/
/*
* 数学运算类,包含了常用的数学计算方法
*
* - 基本运算
* - 乘方/开方
* - 指数/对数
* - 平面坐标
* - 三角函数
* - 双曲函数
* - 舍入操作
* - 绝对值
* - 最大值/最小值
* - 符号函数
* - 浮点数操作
* - 杂项
*/
public final class Math {
/**
* The {@code double} value that is closer than any other to
* <i>e</i>, the base of the natural logarithms.
*/
public static final double E = 2.7182818284590452354;
/**
* The {@code double} value that is closer than any other to
* <i>pi</i>, the ratio of the circumference of a circle to its
* diameter.
*/
public static final double PI = 3.14159265358979323846;
/**
* Constant by which to multiply an angular value in degrees to obtain an angular value in radians.
*/
private static final double DEGREES_TO_RADIANS = 0.017453292519943295;
/**
* Constant by which to multiply an angular value in radians to obtain an angular value in degrees.
*/
private static final double RADIANS_TO_DEGREES = 57.29577951308232;
// Use raw bit-wise conversions on guaranteed non-NaN arguments.
private static final long negativeZeroFloatBits = Float.floatToRawIntBits(-0.0f);
private static final long negativeZeroDoubleBits = Double.doubleToRawLongBits(-0.0d);
// Constants used in scalb
static double twoToTheDoubleScaleUp = powerOfTwoD(512);
static double twoToTheDoubleScaleDown = powerOfTwoD(-512);
/**
* Don't let anyone instantiate this class.
*/
private Math() {
}
/*▼ 基本运算 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns the sum of its arguments,
* throwing an exception if the result overflows an {@code int}.
*
* @param x the first value
* @param y the second value
*
* @return the result
*
* @throws ArithmeticException if the result overflows an int
* @since 1.8
*/
// 加法
@HotSpotIntrinsicCandidate
public static int addExact(int x, int y) {
int r = x + y;
// HD 2-12 Overflow if both arguments have the opposite sign of the result
if(((x ^ r) & (y ^ r))<0) {
throw new ArithmeticException("integer overflow");
}
return r;
}
/**
* Returns the sum of its arguments,
* throwing an exception if the result overflows a {@code long}.
*
* @param x the first value
* @param y the second value
*
* @return the result
*
* @throws ArithmeticException if the result overflows a long
* @since 1.8
*/
// 加法
@HotSpotIntrinsicCandidate
public static long addExact(long x, long y) {
long r = x + y;
// HD 2-12 Overflow iff both arguments have the opposite sign of the result
if(((x ^ r) & (y ^ r))<0) {
throw new ArithmeticException("long overflow");
}
return r;
}
/**
* Returns the difference of the arguments,
* throwing an exception if the result overflows an {@code int}.
*
* @param x the first value
* @param y the second value to subtract from the first
*
* @return the result
*
* @throws ArithmeticException if the result overflows an int
* @since 1.8
*/
// 减法
@HotSpotIntrinsicCandidate
public static int subtractExact(int x, int y) {
int r = x - y;
// HD 2-12 Overflow iff the arguments have different signs and
// the sign of the result is different from the sign of x
if(((x ^ y) & (x ^ r))<0) {
throw new ArithmeticException("integer overflow");
}
return r;
}
/**
* Returns the difference of the arguments,
* throwing an exception if the result overflows a {@code long}.
*
* @param x the first value
* @param y the second value to subtract from the first
*
* @return the result
*
* @throws ArithmeticException if the result overflows a long
* @since 1.8
*/
// 减法
@HotSpotIntrinsicCandidate
public static long subtractExact(long x, long y) {
long r = x - y;
// HD 2-12 Overflow iff the arguments have different signs and
// the sign of the result is different from the sign of x
if(((x ^ y) & (x ^ r))<0) {
throw new ArithmeticException("long overflow");
}
return r;
}
/**
* Returns the product of the arguments,
* throwing an exception if the result overflows an {@code int}.
*
* @param x the first value
* @param y the second value
*
* @return the result
*
* @throws ArithmeticException if the result overflows an int
* @since 1.8
*/
// 乘法
@HotSpotIntrinsicCandidate
public static int multiplyExact(int x, int y) {
long r = (long) x * (long) y;
if((int) r != r) {
throw new ArithmeticException("integer overflow");
}
return (int) r;
}
/**
* Returns the product of the arguments,
* throwing an exception if the result overflows a {@code long}.
*
* @param x the first value
* @param y the second value
*
* @return the result
*
* @throws ArithmeticException if the result overflows a long
* @since 1.8
*/
// 乘法
@HotSpotIntrinsicCandidate
public static long multiplyExact(long x, long y) {
long r = x * y;
long ax = Math.abs(x);
long ay = Math.abs(y);
if(((ax | ay) >>> 31 != 0)) {
// Some bits greater than 2^31 that might cause overflow
// Check the result using the divide operator
// and check for the special case of Long.MIN_VALUE * -1
if(((y != 0) && (r / y != x)) || (x == Long.MIN_VALUE && y == -1)) {
throw new ArithmeticException("long overflow");
}
}
return r;
}
/**
* Returns the product of the arguments, throwing an exception if the result
* overflows a {@code long}.
*
* @param x the first value
* @param y the second value
*
* @return the result
*
* @throws ArithmeticException if the result overflows a long
* @since 9
*/
// 乘法
public static long multiplyExact(long x, int y) {
return multiplyExact(x, (long) y);
}
/**
* Returns the exact mathematical product of the arguments.
*
* @param x the first value
* @param y the second value
*
* @return the result
*
* @since 9
*/
// 乘法
public static long multiplyFull(int x, int y) {
return (long) x * (long) y;
}
/**
* Returns as a {@code long} the most significant 64 bits of the 128-bit product of two 64-bit factors.
*
* @param x the first value
* @param y the second value
*
* @return the result
*
* @since 9
*/
// 乘法,返回两个long乘积的高64位
@HotSpotIntrinsicCandidate
public static long multiplyHigh(long x, long y) {
if(x<0 || y<0) {
// Use technique from section 8-2 of Henry S. Warren, Jr.,
// Hacker's Delight (2nd ed.) (Addison Wesley, 2013), 173-174.
long x1 = x >> 32;
long x2 = x & 0xFFFFFFFFL;
long y1 = y >> 32;
long y2 = y & 0xFFFFFFFFL;
long z2 = x2 * y2;
long t = x1 * y2 + (z2 >>> 32);
long z1 = t & 0xFFFFFFFFL;
long z0 = t >> 32;
z1 += x2 * y1;
return x1 * y1 + z0 + (z1 >> 32);
} else {
// Use Karatsuba technique with two base 2^32 digits.
long x1 = x >>> 32;
long y1 = y >>> 32;
long x2 = x & 0xFFFFFFFFL;
long y2 = y & 0xFFFFFFFFL;
long A = x1 * y1;
long B = x2 * y2;
long C = (x1 + x2) * (y1 + y2);
long K = C - A - B;
return (((B >>> 32) + K) >>> 32) + A;
}
}
/*
* 向下取整除法:
*
* 11/ 8 = 1.375 ==> 1
* -11/ 8 = -1.375 ==> -2
* 11/-8 = -1.375 ==> -2
* -11/-8 = 1.375 ==> 1
*/
/**
* Returns the largest (closest to positive infinity)
* {@code int} value that is less than or equal to the algebraic quotient.
* There is one special case, if the dividend is the
* {@linkplain Integer#MIN_VALUE Integer.MIN_VALUE} and the divisor is {@code -1},
* then integer overflow occurs and
* the result is equal to {@code Integer.MIN_VALUE}.
* <p>
* Normal integer division operates under the round to zero rounding mode
* (truncation). This operation instead acts under the round toward
* negative infinity (floor) rounding mode.
* The floor rounding mode gives different results from truncation
* when the exact result is negative.
* <ul>
* <li>If the signs of the arguments are the same, the results of
* {@code floorDiv} and the {@code /} operator are the same. <br>
* For example, {@code floorDiv(4, 3) == 1} and {@code (4 / 3) == 1}.</li>
* <li>If the signs of the arguments are different, the quotient is negative and
* {@code floorDiv} returns the integer less than or equal to the quotient
* and the {@code /} operator returns the integer closest to zero.<br>
* For example, {@code floorDiv(-4, 3) == -2},
* whereas {@code (-4 / 3) == -1}.
* </li>
* </ul>
*
* @param x the dividend
* @param y the divisor
*
* @return the largest (closest to positive infinity)
* {@code int} value that is less than or equal to the algebraic quotient.
*
* @throws ArithmeticException if the divisor {@code y} is zero
* @see #floorMod(int, int)
* @see #floor(double)
* @since 1.8
*/
// 向下取整除法
public static int floorDiv(int x, int y) {
int r = x / y;
// if the signs are different and modulo not zero, round down
if((x ^ y)<0 && (r * y != x)) {
r--;
}
return r;
}
/**
* Returns the largest (closest to positive infinity)
* {@code long} value that is less than or equal to the algebraic quotient.
* There is one special case, if the dividend is the
* {@linkplain Long#MIN_VALUE Long.MIN_VALUE} and the divisor is {@code -1},
* then integer overflow occurs and
* the result is equal to {@code Long.MIN_VALUE}.
* <p>
* Normal integer division operates under the round to zero rounding mode
* (truncation). This operation instead acts under the round toward
* negative infinity (floor) rounding mode.
* The floor rounding mode gives different results from truncation
* when the exact result is negative.
* <p>
* For examples, see {@link #floorDiv(int, int)}.
*
* @param x the dividend
* @param y the divisor
*
* @return the largest (closest to positive infinity)
* {@code int} value that is less than or equal to the algebraic quotient.
*
* @throws ArithmeticException if the divisor {@code y} is zero
* @see #floorMod(long, int)
* @see #floor(double)
* @since 9
*/
// 向下取整除法
public static long floorDiv(long x, int y) {
return floorDiv(x, (long) y);
}
/**
* Returns the largest (closest to positive infinity)
* {@code long} value that is less than or equal to the algebraic quotient.
* There is one special case, if the dividend is the
* {@linkplain Long#MIN_VALUE Long.MIN_VALUE} and the divisor is {@code -1},
* then integer overflow occurs and
* the result is equal to {@code Long.MIN_VALUE}.
* <p>
* Normal integer division operates under the round to zero rounding mode
* (truncation). This operation instead acts under the round toward
* negative infinity (floor) rounding mode.
* The floor rounding mode gives different results from truncation
* when the exact result is negative.
* <p>
* For examples, see {@link #floorDiv(int, int)}.
*
* @param x the dividend
* @param y the divisor
*
* @return the largest (closest to positive infinity)
* {@code long} value that is less than or equal to the algebraic quotient.
*
* @throws ArithmeticException if the divisor {@code y} is zero
* @see #floorMod(long, long)
* @see #floor(double)
* @since 1.8
*/
// 向下取整除法
public static long floorDiv(long x, long y) {
long r = x / y;
// if the signs are different and modulo not zero, round down
if((x ^ y)<0 && (r * y != x)) {
r--;
}
return r;
}
/*
* 取模运算:
*
* 11 MOD 8 => 从0开始,顺时针前进11步,得到3
* -11 MOD 8 => 从0开始,逆时针前进11步,得到5
*
* 0
* 7 1
* 6 2
* 5 3
* 4
*
*
* 11 MOD -8 => 从0开始,顺时针前进11步,得到-5
* -11 MOD -5 => 从0开始,逆时针前进11步,得到-3
*
* 0
* -1 -7
* -2 -6
* -3 -5
* -4
*/
/**
* Returns the floor modulus of the {@code int} arguments.
* <p>
* The floor modulus is {@code x - (floorDiv(x, y) * y)},
* has the same sign as the divisor {@code y}, and
* is in the range of {@code -abs(y) < r < +abs(y)}.
*
* <p>
* The relationship between {@code floorDiv} and {@code floorMod} is such that:
* <ul>
* <li>{@code floorDiv(x, y) * y + floorMod(x, y) == x}
* </ul>
* <p>
* The difference in values between {@code floorMod} and
* the {@code %} operator is due to the difference between
* {@code floorDiv} that returns the integer less than or equal to the quotient
* and the {@code /} operator that returns the integer closest to zero.
* <p>
* Examples:
* <ul>
* <li>If the signs of the arguments are the same, the results
* of {@code floorMod} and the {@code %} operator are the same. <br>
* <ul>
* <li>{@code floorMod(4, 3) == 1}; and {@code (4 % 3) == 1}</li>
* </ul>
* <li>If the signs of the arguments are different, the results differ from the {@code %} operator.<br>
* <ul>
* <li>{@code floorMod(+4, -3) == -2}; and {@code (+4 % -3) == +1} </li>
* <li>{@code floorMod(-4, +3) == +2}; and {@code (-4 % +3) == -1} </li>
* <li>{@code floorMod(-4, -3) == -1}; and {@code (-4 % -3) == -1 } </li>
* </ul>
* </li>
* </ul>
* <p>
* If the signs of arguments are unknown and a positive modulus
* is needed it can be computed as {@code (floorMod(x, y) + abs(y)) % abs(y)}.
*
* @param x the dividend
* @param y the divisor
*
* @return the floor modulus {@code x - (floorDiv(x, y) * y)}
*
* @throws ArithmeticException if the divisor {@code y} is zero
* @see #floorDiv(int, int)
* @since 1.8
*/
// 取模,相当于(x % y + y) % y
public static int floorMod(int x, int y) {
return x - floorDiv(x, y) * y;
}
/**
* Returns the floor modulus of the {@code long} and {@code int} arguments.
* <p>
* The floor modulus is {@code x - (floorDiv(x, y) * y)},
* has the same sign as the divisor {@code y}, and
* is in the range of {@code -abs(y) < r < +abs(y)}.
*
* <p>
* The relationship between {@code floorDiv} and {@code floorMod} is such that:
* <ul>
* <li>{@code floorDiv(x, y) * y + floorMod(x, y) == x}
* </ul>
* <p>
* For examples, see {@link #floorMod(int, int)}.
*
* @param x the dividend
* @param y the divisor
*
* @return the floor modulus {@code x - (floorDiv(x, y) * y)}
*
* @throws ArithmeticException if the divisor {@code y} is zero
* @see #floorDiv(long, int)
* @since 9
*/
// 取模,相当于(x % y + y) % y
public static int floorMod(long x, int y) {
// Result cannot overflow the range of int.
return (int) (x - floorDiv(x, y) * y);
}
/**
* Returns the floor modulus of the {@code long} arguments.
* <p>
* The floor modulus is {@code x - (floorDiv(x, y) * y)},
* has the same sign as the divisor {@code y}, and
* is in the range of {@code -abs(y) < r < +abs(y)}.
*
* <p>
* The relationship between {@code floorDiv} and {@code floorMod} is such that:
* <ul>
* <li>{@code floorDiv(x, y) * y + floorMod(x, y) == x}
* </ul>
* <p>
* For examples, see {@link #floorMod(int, int)}.
*
* @param x the dividend
* @param y the divisor
*
* @return the floor modulus {@code x - (floorDiv(x, y) * y)}
*
* @throws ArithmeticException if the divisor {@code y} is zero
* @see #floorDiv(long, long)
* @since 1.8
*/
// 取模,相当于(x % y + y) % y
public static long floorMod(long x, long y) {
return x - floorDiv(x, y) * y;
}
/**
* Computes the remainder operation on two arguments as prescribed
* by the IEEE 754 standard.
* The remainder value is mathematically equal to
* <code>f1 - f2</code> × <i>n</i>,
* where <i>n</i> is the mathematical integer closest to the exact
* mathematical value of the quotient {@code f1/f2}, and if two
* mathematical integers are equally close to {@code f1/f2},
* then <i>n</i> is the integer that is even. If the remainder is
* zero, its sign is the same as the sign of the first argument.
* Special cases:
* <ul><li>If either argument is NaN, or the first argument is infinite,
* or the second argument is positive zero or negative zero, then the
* result is NaN.
* <li>If the first argument is finite and the second argument is
* infinite, then the result is the same as the first argument.</ul>
*
* @param f1 the dividend.
* @param f2 the divisor.
*
* @return the remainder when {@code f1} is divided by
* {@code f2}.
*/
/*
* 按照 IEEE 754 标准的规定,对两个参数进行余数运算。
*
* 余数的算术值等于 f1 - f2 × n,其中 n 是最接近商 f1/f2 准确算术值的整数.
* 如果两个整数都同样接近 f1/f2,那么 n 是其中的偶数。
* 如果余数是 0,那么它的符号与第一个参数的符号相同。
*
* 特殊情况如下:
* 如果两个参数都为 NaN,或者第一个参数为无穷大,或者第二个参数为正 0 或负 0,那么结果为 NaN。
* 如果第一个参数为有限值,第二个参数为无穷大,那么结果与第一个参数相同。
*
* 计算结果必须在准确结果的 1 ulp 范围内。如果一个参数保持常量,那么在另一个参数中,结果必须具有半单调性。
*/
public static double IEEEremainder(double f1, double f2) {
return StrictMath.IEEEremainder(f1, f2); // delegate to StrictMath
}
/**
* Returns the argument incremented by one, throwing an exception if the
* result overflows an {@code int}.
*
* @param a the value to increment
*
* @return the result
*
* @throws ArithmeticException if the result overflows an int
* @since 1.8
*/
// a+1
@HotSpotIntrinsicCandidate
public static int incrementExact(int a) {
if(a == Integer.MAX_VALUE) {
throw new ArithmeticException("integer overflow");
}
return a + 1;
}
/**
* Returns the argument incremented by one, throwing an exception if the
* result overflows a {@code long}.
*
* @param a the value to increment
*
* @return the result
*
* @throws ArithmeticException if the result overflows a long
* @since 1.8
*/
// a+1
@HotSpotIntrinsicCandidate
public static long incrementExact(long a) {
if(a == Long.MAX_VALUE) {
throw new ArithmeticException("long overflow");
}
return a + 1L;
}
/**
* Returns the argument decremented by one, throwing an exception if the
* result overflows an {@code int}.
*
* @param a the value to decrement
*
* @return the result
*
* @throws ArithmeticException if the result overflows an int
* @since 1.8
*/
// a-1
@HotSpotIntrinsicCandidate
public static int decrementExact(int a) {
if(a == Integer.MIN_VALUE) {
throw new ArithmeticException("integer overflow");
}
return a - 1;
}
/**
* Returns the argument decremented by one, throwing an exception if the
* result overflows a {@code long}.
*
* @param a the value to decrement
*
* @return the result
*
* @throws ArithmeticException if the result overflows a long
* @since 1.8
*/
// a-1
@HotSpotIntrinsicCandidate
public static long decrementExact(long a) {
if(a == Long.MIN_VALUE) {
throw new ArithmeticException("long overflow");
}
return a - 1L;
}
/**
* Returns the negation of the argument, throwing an exception if the
* result overflows an {@code int}.
*
* @param a the value to negate
*
* @return the result
*
* @throws ArithmeticException if the result overflows an int
* @since 1.8
*/
// -a
@HotSpotIntrinsicCandidate
public static int negateExact(int a) {
if(a == Integer.MIN_VALUE) {
throw new ArithmeticException("integer overflow");
}
return -a;
}
/**
* Returns the negation of the argument, throwing an exception if the
* result overflows a {@code long}.
*
* @param a the value to negate
*
* @return the result
*
* @throws ArithmeticException if the result overflows a long
* @since 1.8
*/
// -a
@HotSpotIntrinsicCandidate
public static long negateExact(long a) {
if(a == Long.MIN_VALUE) {
throw new ArithmeticException("long overflow");
}
return -a;
}
/**
* Returns the fused multiply add of the three arguments; that is,
* returns the exact product of the first two arguments summed
* with the third argument and then rounded once to the nearest
* {@code double}.
*
* The rounding is done using the {@linkplain
* java.math.RoundingMode#HALF_EVEN round to nearest even
* rounding mode}.
*
* In contrast, if {@code a * b + c} is evaluated as a regular
* floating-point expression, two rounding errors are involved,
* the first for the multiply operation, the second for the
* addition operation.
*
* <p>Special cases:
* <ul>
* <li> If any argument is NaN, the result is NaN.
*
* <li> If one of the first two arguments is infinite and the
* other is zero, the result is NaN.
*
* <li> If the exact product of the first two arguments is infinite
* (in other words, at least one of the arguments is infinite and
* the other is neither zero nor NaN) and the third argument is an
* infinity of the opposite sign, the result is NaN.
*
* </ul>
*
* <p>Note that {@code fma(a, 1.0, c)} returns the same
* result as ({@code a + c}). However,
* {@code fma(a, b, +0.0)} does <em>not</em> always return the
* same result as ({@code a * b}) since
* {@code fma(-0.0, +0.0, +0.0)} is {@code +0.0} while
* ({@code -0.0 * +0.0}) is {@code -0.0}; {@code fma(a, b, -0.0)} is
* equivalent to ({@code a * b}) however.
*
* @param a a value
* @param b a value
* @param c a value
*
* @return (< i > a < / i > & nbsp ; & times ; & nbsp ; < i > b < / i > & nbsp ; + & nbsp ; < i > c < / i >)
* computed, as if with unlimited range and precision, and rounded
* once to the nearest {@code double} value
*
* @apiNote This method corresponds to the fusedMultiplyAdd
* operation defined in IEEE 754-2008.
* @since 9
*/
// 计算a*b+c
@HotSpotIntrinsicCandidate
public static double fma(double a, double b, double c) {
/*
* Infinity and NaN arithmetic is not quite the same with two
* roundings as opposed to just one so the simple expression
* "a * b + c" cannot always be used to compute the correct
* result. With two roundings, the product can overflow and
* if the addend is infinite, a spurious NaN can be produced
* if the infinity from the overflow and the infinite addend
* have opposite signs.
*/
// First, screen for and handle non-finite input values whose
// arithmetic is not supported by BigDecimal.
if(Double.isNaN(a) || Double.isNaN(b) || Double.isNaN(c)) {
return Double.NaN;
} else { // All inputs non-NaN
boolean infiniteA = Double.isInfinite(a);
boolean infiniteB = Double.isInfinite(b);
boolean infiniteC = Double.isInfinite(c);
double result;
if(infiniteA || infiniteB || infiniteC) {
if(infiniteA && b == 0.0 || infiniteB && a == 0.0) {
return Double.NaN;
}
// Store product in a double field to cause an
// overflow even if non-strictfp evaluation is being
// used.
double product = a * b;
if(Double.isInfinite(product) && !infiniteA && !infiniteB) {
// Intermediate overflow; might cause a
// spurious NaN if added to infinite c.
assert Double.isInfinite(c);
return c;
} else {
result = product + c;
assert !Double.isFinite(result);
return result;
}
} else { // All inputs finite
BigDecimal product = (new BigDecimal(a)).multiply(new BigDecimal(b));
if(c == 0.0) { // Positive or negative zero
// If the product is an exact zero, use a
// floating-point expression to compute the sign
// of the zero final result. The product is an
// exact zero if and only if at least one of a and
// b is zero.
if(a == 0.0 || b == 0.0) {
return a * b + c;
} else {
// The sign of a zero addend doesn't matter if
// the product is nonzero. The sign of a zero
// addend is not factored in the result if the
// exact product is nonzero but underflows to
// zero; see IEEE-754 2008 section 6.3 "The
// sign bit".
return product.doubleValue();
}
} else {
return product.add(new BigDecimal(c)).doubleValue();
}
}
}
}
/**
* Returns the fused multiply add of the three arguments; that is,
* returns the exact product of the first two arguments summed
* with the third argument and then rounded once to the nearest
* {@code float}.
*
* The rounding is done using the {@linkplain
* java.math.RoundingMode#HALF_EVEN round to nearest even
* rounding mode}.
*
* In contrast, if {@code a * b + c} is evaluated as a regular
* floating-point expression, two rounding errors are involved,
* the first for the multiply operation, the second for the
* addition operation.
*
* <p>Special cases:
* <ul>
* <li> If any argument is NaN, the result is NaN.
*
* <li> If one of the first two arguments is infinite and the
* other is zero, the result is NaN.
*
* <li> If the exact product of the first two arguments is infinite
* (in other words, at least one of the arguments is infinite and
* the other is neither zero nor NaN) and the third argument is an
* infinity of the opposite sign, the result is NaN.
*
* </ul>
*
* <p>Note that {@code fma(a, 1.0f, c)} returns the same
* result as ({@code a + c}). However,
* {@code fma(a, b, +0.0f)} does <em>not</em> always return the
* same result as ({@code a * b}) since
* {@code fma(-0.0f, +0.0f, +0.0f)} is {@code +0.0f} while
* ({@code -0.0f * +0.0f}) is {@code -0.0f}; {@code fma(a, b, -0.0f)} is
* equivalent to ({@code a * b}) however.
*
* @param a a value
* @param b a value
* @param c a value
*
* @return (< i > a < / i > & nbsp ; & times ; & nbsp ; < i > b < / i > & nbsp ; + & nbsp ; < i > c < / i >)
* computed, as if with unlimited range and precision, and rounded
* once to the nearest {@code float} value
*
* @apiNote This method corresponds to the fusedMultiplyAdd
* operation defined in IEEE 754-2008.
* @since 9
*/
// 计算a*b+c
@HotSpotIntrinsicCandidate
public static float fma(float a, float b, float c) {
/*
* Since the double format has more than twice the precision
* of the float format, the multiply of a * b is exact in
* double. The add of c to the product then incurs one
* rounding error. Since the double format moreover has more
* than (2p + 2) precision bits compared to the p bits of the
* float format, the two roundings of (a * b + c), first to
* the double format and then secondarily to the float format,
* are equivalent to rounding the intermediate result directly
* to the float format.
*
* In terms of strictfp vs default-fp concerns related to
* overflow and underflow, since
*
* (Float.MAX_VALUE * Float.MAX_VALUE) << Double.MAX_VALUE
* (Float.MIN_VALUE * Float.MIN_VALUE) >> Double.MIN_VALUE
*
* neither the multiply nor add will overflow or underflow in
* double. Therefore, it is not necessary for this method to
* be declared strictfp to have reproducible
* behavior. However, it is necessary to explicitly store down
* to a float variable to avoid returning a value in the float
* extended value set.
*/
float result = (float) (((double) a * (double) b) + (double) c);
return result;
}