-
Notifications
You must be signed in to change notification settings - Fork 13
/
EDecimal.cs
6783 lines (6528 loc) · 310 KB
/
EDecimal.cs
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
/*
Written by Peter O.
Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/
If you like this, you should donate to Peter O.
at: http://peteroupc.github.io/
*/
using System;
using System.Text;
/*
TODO: In next major version, maybe convert EDecimal.One/Ten/Zero to fields
rather than properties
*/
namespace PeterO.Numbers {
/// <summary>
/// Represents an arbitrary-precision decimal
/// floating-point number. (The "E" stands for "extended",
/// meaning that instances of this class can be values
/// other than numbers proper, such as infinity and
/// not-a-number.)
/// <para><b>About decimal arithmetic</b>
/// </para>
/// <para>Decimal (base-10) arithmetic, such as that provided by this
/// class, is appropriate for calculations involving such real-world
/// data as prices and other sums of money, tax rates, and
/// measurements. These calculations often involve multiplying or
/// dividing one decimal with another decimal, or performing other
/// operations on decimal numbers. Many of these calculations also rely
/// on rounding behavior in which the result after rounding is an
/// arbitrary-precision decimal number (for example, multiplying a
/// price by a premium rate, then rounding, should result in a decimal
/// amount of money).</para>
/// <para>On the other hand, most implementations of <c>float</c>
/// and
/// <c>double</c>
/// , including in C# and Java, store numbers in a binary
/// (base-2) floating-point format and use binary floating-point
/// arithmetic. Many decimal numbers can't be represented exactly in
/// binary floating-point format (regardless of its length). Applying
/// binary arithmetic to numbers intended to be decimals can sometimes
/// lead to unintuitive results, as is shown in the description for the
/// FromDouble() method of this class.</para>
/// <para><b>About EDecimal instances</b>
/// </para>
/// <para>Each instance of this class consists of an integer
/// significand and an integer exponent, both arbitrary-precision. The
/// value of the number equals significand * 10^exponent.</para>
/// <para>The significand is the value of the digits that make up a
/// number, ignoring the decimal point and exponent. For example, in
/// the number 2356.78, the significand is 235678. The exponent is
/// where the "floating" decimal point of the number is located. A
/// positive exponent means "move it to the right", and a negative
/// exponent means "move it to the left." In the example 2, 356.78, the
/// exponent is -2, since it has 2 decimal places and the decimal point
/// is "moved to the left by 2." Therefore, in the arbitrary-precision
/// decimal representation, this number would be stored as 235678 *
/// 10^-2.</para>
/// <para>The significand and exponent format preserves trailing zeros
/// in the number's value. This may give rise to multiple ways to store
/// the same value. For example, 1.00 and 1 would be stored
/// differently, even though they have the same value. In the first
/// case, 100 * 10^-2 (100 with decimal point moved left by 2), and in
/// the second case, 1 * 10^0 (1 with decimal point moved 0).</para>
/// <para>This class also supports values for negative zero,
/// not-a-number (NaN) values, and infinity. <b>Negative zero</b>
/// is
/// generally used when a negative number is rounded to 0; it has the
/// same mathematical value as positive zero. <b>Infinity</b>
/// is
/// generally used when a non-zero number is divided by zero, or when a
/// very high or very low number can't be represented in a given
/// exponent range. <b>Not-a-number</b>
/// is generally used to signal
/// errors.</para>
/// <para>This class implements the General Decimal Arithmetic
/// Specification version 1.70 except part of chapter 6(
/// <c>http://speleotrove.com/decimal/decarith.html</c>
/// ).</para>
/// <para><b>Errors and Exceptions</b>
/// </para>
/// <para>Passing a signaling NaN to any arithmetic operation shown
/// here will signal the flag FlagInvalid and return a quiet NaN, even
/// if another operand to that operation is a quiet NaN, unless the
/// operation's documentation expressly states that another result
/// happens when a signaling NaN is passed to that operation.</para>
/// <para>Passing a quiet NaN to any arithmetic operation shown here
/// will return a quiet NaN, unless the operation's documentation
/// expressly states that another result happens when a quiet NaN is
/// passed to that operation. Invalid operations will also return a
/// quiet NaN, as stated in the individual methods.</para>
/// <para>Unless noted otherwise, passing a null arbitrary-precision
/// decimal argument to any method here will throw an exception.</para>
/// <para>When an arithmetic operation signals the flag FlagInvalid,
/// FlagOverflow, or FlagDivideByZero, it will not throw an exception
/// too, unless the flag's trap is enabled in the arithmetic context
/// (see EContext's Traps property).</para>
/// <para>If an operation requires creating an intermediate value that
/// might be too big to fit in memory (or might require more than 2
/// gigabytes of memory to store -- due to the current use of a 32-bit
/// integer internally as a length), the operation may signal an
/// invalid-operation flag and return not-a-number (NaN). In certain
/// rare cases, the CompareTo method may throw OutOfMemoryException
/// (called OutOfMemoryError in Java) in the same circumstances.</para>
/// <para><b>Serialization</b>
/// </para>
/// <para>An arbitrary-precision decimal value can be serialized
/// (converted to a stable format) in one of the following ways:</para>
/// <list><item>By calling the toString() method, which will always
/// return distinct strings for distinct arbitrary-precision decimal
/// values.</item>
/// <item>By calling the UnsignedMantissa, Exponent, and
/// IsNegative properties, and calling the IsInfinity, IsQuietNaN, and
/// IsSignalingNaN methods. The return values combined will uniquely
/// identify a particular arbitrary-precision decimal value.</item>
/// </list>
/// <para><b>Thread safety</b>
/// </para>
/// <para>Instances of this class are immutable, so they are inherently
/// safe for use by multiple threads. Multiple instances of this object
/// with the same properties are interchangeable, so they should not be
/// compared using the "==" operator (which might only check if each
/// side of the operator is the same instance).</para>
/// <para><b>Comparison considerations</b>
/// </para>
/// <para>This class's natural ordering (under the CompareTo method) is
/// not consistent with the Equals method. This means that two values
/// that compare as equal under the CompareTo method might not be equal
/// under the Equals method. The CompareTo method compares the
/// mathematical values of the two instances passed to it (and
/// considers two different NaN values as equal), while two instances
/// with the same mathematical value, but different exponents, will be
/// considered unequal under the Equals method.</para>
/// <para><b>Security note</b>
/// </para>
/// <para>It is not recommended to implement security-sensitive
/// algorithms using the methods in this class, for several
/// reasons:</para>
/// <list><item><c>EDecimal</c>
/// objects are immutable, so they can't be
/// modified, and the memory they occupy is not guaranteed to be
/// cleared in a timely fashion due to garbage collection. This is
/// relevant for applications that use many-digit-long numbers as
/// secret parameters.</item>
/// <item>The methods in this class
/// (especially those that involve arithmetic) are not guaranteed to be
/// "constant-time" (non-data-dependent) for all relevant inputs.
/// Certain attacks that involve encrypted communications have
/// exploited the timing and other aspects of such communications to
/// derive keying material or cleartext indirectly.</item>
/// </list>
/// <para>Applications should instead use dedicated security libraries
/// to handle big numbers in security-sensitive algorithms.</para>
/// <para><b>Reproducibility note</b>
/// </para>
/// <para>Some applications, such as simulations, care about results
/// that are reproducible, bit for bit, across computers and across
/// runs of the application. Bruce Dawson, in "Floating-Point
/// Determinism" ( <c>https://randomascii.wordpress.com/</c>
/// <c>2013/07/16/floating-point-determinism/</c>
/// ), identified many
/// reproducibility issues with floating-point numbers, and here is how
/// they relate to the EDecimal and EFloat classes of this
/// library:</para>
/// <list><item>Runtime floating-point settings: All the settings that
/// change how EDecimal and EFloat behave are given as parameters to
/// the appropriate methods, especially via EContext objects, which
/// specify the precision, rounding, and exponent range of numbers,
/// among other things. The EDecimal and EFloat classes avoid the use
/// of "native" floating-point data types (except for methods that
/// convert to or from <c>float</c>
/// , <c>double</c>
/// , or
/// <c>System.Decimal</c>
/// ). Such "native" types are often subject to
/// runtime settings that change how floating-point math behaves with
/// them, and these settings are often not accessible to .NET or Java
/// code.</item>
/// <item>Non-associativity and intermediate precisions:
/// In general, EDecimal and EFloat use "unlimited" precision in their
/// calculations unless specified otherwise by an EContext object.
/// However, by limiting the precision of EDecimal, EFloat, and other
/// floating-point numbers in this way, operations such as addition and
/// multiplication on three or more numbers can be
/// <i>non-associative</i>
/// , meaning the result can change depending on
/// the order in which those numbers are added or multiplied. This
/// property means that if an algorithm does not ensure such numbers
/// are added or multiplied in the same order every time, its results
/// may not be reproducible across computers or across runs of the
/// application. This non-associativity problem can happen, for
/// example, if an application splits a calculation across several
/// threads and combines their results in the end. The problems with an
/// unspecified order of operations (in the same line of code) and
/// intermediate precisions (problems present in C and C++, for
/// example) don't exist with method calls to EDecimal and EFloat
/// methods, especially since they require limited-precision support to
/// be declared explicitly via EContext.</item>
/// <item>fmadd
/// instruction: EDecimal and EFloat include a MultiplyAndAdd method
/// with the same semantics as in the General Decimal Arithmetic
/// Specification, which requires delivering correctly rounded results
/// for this method.</item>
/// <item>Square root estimate: Not applicable
/// since EDecimal and EFloat don't include any estimates to square
/// root.</item>
/// <item>Transcendental functions: This includes
/// logarithms, exponentials, and the Pi method. For these functions,
/// results are not guaranteed to always be correctly rounded. When
/// using transcendentals, an application that cares about
/// reproducibility should choose one version of this library and stick
/// to it; this at least has the advantage that the implementation will
/// be the same across computers, unlike with "native" floating-point
/// types where the choice of implementation is often not within the
/// application's control.</item>
/// <item>Conversions: Conversions
/// between EDecimal or EFloat and text strings have the same
/// implementation across computers for the same version of this
/// library (see also the advice for transcendentals above). But as for
/// the ToDouble, ToSingle, FromDouble, and FromSingle methods, note
/// that some implementations of Java and.NET may or may not support
/// preserving the value of subnormal numbers (numbers other than zero
/// with the lowest possible exponent) or the payloads held in a
/// not-a-number (NaN) value of float or double; thus these methods
/// should not be considered reproducible across computers.</item>
/// <item>Compiler differences: Not applicable where these classes
/// don't use "native" floating-point types.</item>
/// <item>Uninitialized
/// data; per-processor code: Not applicable.</item>
/// </list>
/// <para><b>Forms of numbers</b>
/// </para>
/// <para>There are several other types of numbers that are mentioned
/// in this class and elsewhere in this documentation. For reference,
/// they are specified here.</para>
/// <para><b>Unsigned integer</b>
/// : An integer that's always 0 or
/// greater, with the following maximum values:</para>
/// <list><item>8-bit unsigned integer, or <i>byte</i>
/// : 255.</item>
/// <item>16-bit unsigned integer: 65535.</item>
/// <item>32-bit unsigned
/// integer: (2 <sup>32</sup>
/// -1).</item>
/// <item>64-bit unsigned
/// integer: (2 <sup>64</sup>
/// -1).</item>
/// </list>
/// <para><b>Signed integer</b>
/// : An integer in <i>two's-complement
/// form</i>
/// , with the following ranges:</para>
/// <list><item>8-bit signed integer: -128 to 127.</item>
/// <item>16-bit
/// signed integer: -32768 to 32767.</item>
/// <item>32-bit signed
/// integer: -2 <sup>31</sup>
/// to (2 <sup>31</sup>
/// - 1).</item>
/// <item>64-bit signed integer: -2 <sup>63</sup>
/// to (2 <sup>63</sup>
/// -
/// 1).</item>
/// </list>
/// <para><b>Two's complement form</b>
/// : In <i>two's-complement
/// form</i>
/// , nonnegative numbers have the highest (most significant)
/// bit set to zero, and negative numbers have that bit (and all bits
/// beyond) set to one, and a negative number is stored in such form by
/// decreasing its absolute value by 1 and swapping the bits of the
/// resulting number.</para>
/// <para><b>64-bit floating-point number</b>
/// : A 64-bit binary
/// floating-point number, in the form <i>significand</i>
/// * 2
/// <sup><i>exponent</i>
/// </sup>
/// . The significand is 53 bits long
/// (Precision) and the exponent ranges from -1074 (EMin) to 971
/// (EMax). The number is stored in the following format (commonly
/// called the IEEE 754 format):</para>
/// <code>|C|BBB...BBB|AAAAAA...AAAAAA|</code>
/// <list><item>A. Low 52 bits (Precision minus 1 bits): Lowest bits of
/// the significand.</item>
/// <item>B. Next 11 bits: Exponent area:
/// <list><item>If all bits are ones, the final stored value is
/// infinity (positive or negative depending on the C bit) if all bits
/// in area A are zeros, or not-a-number (NaN) otherwise.</item>
/// <item>If all bits are zeros, the final stored value is a subnormal
/// number, the exponent is EMin, and the highest bit of the
/// significand is zero.</item>
/// <item>If any other number, the exponent
/// is this value reduced by 1, then raised by EMin, and the highest
/// bit of the significand is one.</item>
/// </list>
/// </item>
/// <item>C.
/// Highest bit: If one, this is a negative number.</item>
/// </list>
/// <para>The elements described above are in the same order as the
/// order of each bit of each element, that is, either most significant
/// first or least significant first.</para>
/// <para><b>32-bit binary floating-point number</b>
/// : A 32-bit binary
/// number which is stored similarly to a <i>64-bit floating-point
/// number</i>
/// , except that:</para>
/// <list><item>Precision is 24 bits.</item>
/// <item>EMin is -149.</item>
/// <item>EMax is 104.</item>
/// <item>A. The low 23 bits (Precision minus
/// 1 bits) are the lowest bits of the significand.</item>
/// <item>B. The
/// next 8 bits are the exponent area.</item>
/// <item>C. If the highest
/// bit is one, this is a negative number.</item>
/// </list>
/// <para><b>.NET Framework decimal</b>
/// : A 128-bit decimal
/// floating-point number, in the form <i>significand</i>
/// * 10 <sup>-
/// <i>scale</i>
/// </sup>
/// , where the scale ranges from 0 to 28. The
/// number is stored in the following format:</para>
/// <list><item>Low 96 bits are the significand, as a 96-bit unsigned
/// integer (all 96-bit values are allowed, up to (2 <sup>96</sup>
/// -1)).</item>
/// <item>Next 16 bits are unused.</item>
/// <item>Next 8
/// bits are the scale, stored as an 8-bit unsigned integer.</item>
/// <item>Next 7 bits are unused.</item>
/// <item>If the highest bit is
/// one, it's a negative number.</item>
/// </list>
/// <para>The elements described above are in the same order as the
/// order of each bit of each element, that is, either most significant
/// first or least significant first.</para>
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Design",
"CA1036",
Justification = "Awaiting advice at dotnet/dotnet-api-docs#2937.")]
public sealed partial class EDecimal : IComparable<EDecimal>,
IEquatable<EDecimal> {
private const int RepeatDivideThreshold = 10000;
internal const int MaxSafeInt = 214748363;
//----------------------------------------------------------------
/// <summary>A not-a-number value.</summary>
#if CODE_ANALYSIS
[System.Diagnostics.CodeAnalysis.SuppressMessage ("Microsoft.Security",
"CA2104", Justification = "EDecimal is immutable")]
#endif
public static readonly EDecimal NaN = CreateWithFlags(
EInteger.Zero,
EInteger.Zero,
(byte)BigNumberFlags.FlagQuietNaN);
/// <summary>Negative infinity, less than any other number.</summary>
#if CODE_ANALYSIS
[System.Diagnostics.CodeAnalysis.SuppressMessage ("Microsoft.Security",
"CA2104", Justification = "EDecimal is immutable")]
#endif
public static readonly EDecimal NegativeInfinity =
CreateWithFlags(
EInteger.Zero,
EInteger.Zero,
BigNumberFlags.FlagInfinity | BigNumberFlags.FlagNegative);
/// <summary>Represents the number negative zero.</summary>
#if CODE_ANALYSIS
[System.Diagnostics.CodeAnalysis.SuppressMessage ("Microsoft.Security",
"CA2104", Justification = "EDecimal is immutable")]
#endif
public static readonly EDecimal NegativeZero =
CreateWithFlags(
EInteger.Zero,
EInteger.Zero,
BigNumberFlags.FlagNegative);
/// <summary>Represents the number 1.</summary>
#if CODE_ANALYSIS
[System.Diagnostics.CodeAnalysis.SuppressMessage ("Microsoft.Security",
"CA2104", Justification = "EDecimal is immutable")]
#endif
public static readonly EDecimal One = new EDecimal(
FastIntegerFixed.FromInt32(1),
FastIntegerFixed.Zero,
(byte)0);
/// <summary>Positive infinity, greater than any other
/// number.</summary>
#if CODE_ANALYSIS
[System.Diagnostics.CodeAnalysis.SuppressMessage ("Microsoft.Security",
"CA2104", Justification = "EDecimal is immutable")]
#endif
public static readonly EDecimal PositiveInfinity =
CreateWithFlags(
EInteger.Zero,
EInteger.Zero,
BigNumberFlags.FlagInfinity);
/// <summary>A not-a-number value that signals an invalid operation
/// flag when it's passed as an argument to any arithmetic operation in
/// arbitrary-precision decimal.</summary>
#if CODE_ANALYSIS
[System.Diagnostics.CodeAnalysis.SuppressMessage ("Microsoft.Security",
"CA2104", Justification = "EDecimal is immutable")]
#endif
public static readonly EDecimal SignalingNaN =
CreateWithFlags(
EInteger.Zero,
EInteger.Zero,
BigNumberFlags.FlagSignalingNaN);
/// <summary>Represents the number 10.</summary>
#if CODE_ANALYSIS
[System.Diagnostics.CodeAnalysis.SuppressMessage ("Microsoft.Security",
"CA2104", Justification = "EDecimal is immutable")]
#endif
public static readonly EDecimal Ten = new EDecimal(
FastIntegerFixed.FromInt32(10),
FastIntegerFixed.Zero,
(byte)0);
/// <summary>Represents the number 0.</summary>
#if CODE_ANALYSIS
[System.Diagnostics.CodeAnalysis.SuppressMessage ("Microsoft.Security",
"CA2104", Justification = "EDecimal is immutable")]
#endif
public static readonly EDecimal Zero = new EDecimal(
FastIntegerFixed.Zero,
FastIntegerFixed.Zero,
(byte)0);
private const int CacheFirst = -24;
private const int CacheLast = 128;
private static readonly EDecimal[] Cache = EDecimalCache(CacheFirst,
CacheLast);
internal static EDecimal FromCache(int v) {
return Cache[v - CacheFirst];
}
private static EDecimal[] EDecimalCache(int first, int last) {
#if DEBUG
if (first < -65535) {
throw new ArgumentException("first (" + first + ") is not greater" +
"\u0020or equal" + "\u0020to " + (-65535));
}
if (first > 65535) {
throw new ArgumentException("first (" + first + ") is not less or" +
"\u0020equal to" + "\u002065535");
}
if (last < -65535) {
throw new ArgumentException("last (" + last + ") is not greater or" +
"\u0020equal" + "\u0020to " + (-65535));
}
if (last > 65535) {
throw new ArgumentException("last (" + last + ") is not less or" +
"\u0020equal to" + "65535");
}
#endif
var cache = new EDecimal[(last - first) + 1];
int i;
for (i = first; i <= last; ++i) {
if (i == 0) {
cache[i - first] = Zero;
} else if (i == 1) {
cache[i - first] = One;
} else if (i == 10) {
cache[i - first] = Ten;
} else {
cache[i - first] = new EDecimal(
FastIntegerFixed.FromInt32(Math.Abs(i)),
FastIntegerFixed.Zero,
(byte)(i < 0 ? BigNumberFlags.FlagNegative : 0));
}
}
return cache;
}
private static readonly DecimalMathHelper HelperValue = new
DecimalMathHelper();
private static readonly IRadixMath<EDecimal> ExtendedMathValue = new
RadixMath<EDecimal>(HelperValue);
//----------------------------------------------------------------
private static readonly IRadixMath<EDecimal> MathValue = new
TrappableRadixMath<EDecimal>(
new ExtendedOrSimpleRadixMath<EDecimal>(HelperValue));
private static readonly int[] ValueTenPowers = {
1, 10, 100, 1000, 10000, 100000,
1000000, 10000000, 100000000,
1000000000,
};
private readonly FastIntegerFixed unsignedMantissa;
private readonly FastIntegerFixed exponent;
private readonly byte flags;
internal EDecimal(
FastIntegerFixed unsignedMantissa,
FastIntegerFixed exponent,
byte flags) {
#if DEBUG
if (unsignedMantissa == null) {
throw new ArgumentNullException(nameof(unsignedMantissa));
}
if (exponent == null) {
throw new ArgumentNullException(nameof(exponent));
}
if (unsignedMantissa.Sign < 0) {
throw new ArgumentException("unsignedMantissa is less than 0.");
}
#endif
this.unsignedMantissa = unsignedMantissa;
this.exponent = exponent;
this.flags = flags;
}
/// <summary>Creates a copy of this arbitrary-precision binary
/// number.</summary>
/// <returns>An arbitrary-precision decimal floating-point
/// number.</returns>
public EDecimal Copy() {
return new EDecimal(
this.unsignedMantissa.Copy(),
this.exponent.Copy(),
this.flags);
}
/// <summary>Gets this object's exponent. This object's value will be
/// an integer if the exponent is positive or zero.</summary>
/// <value>This object's exponent. This object's value will be an
/// integer if the exponent is positive or zero.</value>
public EInteger Exponent {
get {
return this.exponent.ToEInteger();
}
}
/// <summary>Gets a value indicating whether this object is finite (not
/// infinity or NaN).</summary>
/// <value><c>true</c> if this object is finite (not infinity or NaN);
/// otherwise, <c>false</c>.</value>
public bool IsFinite {
get {
return (this.flags & (BigNumberFlags.FlagInfinity |
BigNumberFlags.FlagNaN)) == 0;
}
}
/// <summary>Gets a value indicating whether this object is negative,
/// including negative zero.</summary>
/// <value><c>true</c> if this object is negative, including negative
/// zero; otherwise, <c>false</c>.</value>
public bool IsNegative {
get {
return (this.flags & BigNumberFlags.FlagNegative) != 0;
}
}
/// <summary>Gets a value indicating whether this object's value equals
/// 0.</summary>
/// <value><c>true</c> if this object's value equals 0; otherwise,
/// <c>false</c>. <c>true</c> if this object's value equals 0;
/// otherwise, <c>false</c>.</value>
public bool IsZero {
get {
return ((this.flags & BigNumberFlags.FlagSpecial) == 0) &&
this.unsignedMantissa.IsValueZero;
}
}
/// <summary>Returns whether this object's value is an
/// integer.</summary>
/// <returns><c>true</c> if this object's value is an integer;
/// otherwise, <c>false</c>.</returns>
public bool IsInteger() {
if (!this.IsFinite) {
return false;
}
if (this.IsZero || this.exponent.CompareToInt(0) >= 0) {
return true;
} else {
EDecimal r = this.Reduce(null);
return r.exponent.CompareToInt(0) >= 0;
}
}
/// <summary>Gets this object's unscaled value, or significand, and
/// makes it negative if this object is negative. If this value is
/// not-a-number (NaN), that value's absolute value is the NaN's
/// "payload" (diagnostic information).</summary>
/// <value>This object's unscaled value. Will be negative if this
/// object's value is negative (including a negative NaN).</value>
public EInteger Mantissa {
get {
return this.IsNegative ? this.unsignedMantissa.ToEInteger().Negate() :
this.unsignedMantissa.ToEInteger();
}
}
/// <summary>Gets this value's sign: -1 if negative; 1 if positive; 0
/// if zero.</summary>
/// <value>This value's sign: -1 if negative; 1 if positive; 0 if
/// zero.</value>
public int Sign {
get {
return (((this.flags & BigNumberFlags.FlagSpecial) == 0) &&
this.unsignedMantissa.IsValueZero) ? 0 : (((this.flags &
BigNumberFlags.FlagNegative) != 0) ? -1 : 1);
}
}
/// <summary>Gets the absolute value of this object's unscaled value,
/// or significand. If this value is not-a-number (NaN), that value is
/// the NaN's "payload" (diagnostic information).</summary>
/// <value>The absolute value of this object's unscaled value.</value>
public EInteger UnsignedMantissa {
get {
return this.unsignedMantissa.ToEInteger();
}
}
internal static EDecimal ChangeExponent(EDecimal ret, EInteger exponent) {
return new EDecimal(
ret.unsignedMantissa,
FastIntegerFixed.FromBig(exponent),
(byte)ret.flags);
}
/// <summary>Returns a number with the value
/// <c>exponent*10^significand</c>.</summary>
/// <param name='mantissaSmall'>Desired value for the
/// significand.</param>
/// <param name='exponentSmall'>Desired value for the exponent.</param>
/// <returns>An arbitrary-precision decimal number.</returns>
public static EDecimal Create(int mantissaSmall, int exponentSmall) {
if (exponentSmall == 0 && mantissaSmall >= CacheFirst &&
mantissaSmall <= CacheLast) {
return Cache[mantissaSmall - CacheFirst];
}
if (mantissaSmall < 0) {
if (mantissaSmall == Int32.MinValue) {
FastIntegerFixed fi = FastIntegerFixed.FromInt64(Int32.MinValue);
return new EDecimal(
fi.Negate(),
FastIntegerFixed.FromInt32(exponentSmall),
(byte)BigNumberFlags.FlagNegative);
}
return new EDecimal(
FastIntegerFixed.FromInt32(-mantissaSmall),
FastIntegerFixed.FromInt32(exponentSmall),
(byte)BigNumberFlags.FlagNegative);
} else if (mantissaSmall == 0) {
return new EDecimal(
FastIntegerFixed.Zero,
FastIntegerFixed.FromInt32(exponentSmall),
(byte)0);
} else {
return new EDecimal(
FastIntegerFixed.FromInt32(mantissaSmall),
FastIntegerFixed.FromInt32(exponentSmall),
(byte)0);
}
}
/// <summary>Creates a number with the value
/// <c>exponent*10^significand</c>.</summary>
/// <param name='mantissa'>Desired value for the significand.</param>
/// <param name='exponentSmall'>Desired value for the exponent.</param>
/// <returns>An arbitrary-precision decimal number.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='mantissa'/> is null.</exception>
public static EDecimal Create(
EInteger mantissa,
int exponentSmall) {
if (mantissa == null) {
throw new ArgumentNullException(nameof(mantissa));
}
if (mantissa.CanFitInInt32()) {
int mantissaSmall = mantissa.ToInt32Checked();
return Create(mantissaSmall, exponentSmall);
}
FastIntegerFixed fi = FastIntegerFixed.FromBig(mantissa);
int sign = fi.Sign;
return new EDecimal(
sign < 0 ? fi.Negate() : fi,
FastIntegerFixed.FromInt32(exponentSmall),
(byte)((sign < 0) ? BigNumberFlags.FlagNegative : 0));
}
/// <summary>Creates a number with the value
/// <c>exponent*10^significand</c>.</summary>
/// <param name='mantissa'>Desired value for the significand.</param>
/// <param name='exponentLong'>Desired value for the exponent.</param>
/// <returns>An arbitrary-precision decimal number.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='mantissa'/> is null.</exception>
public static EDecimal Create(
EInteger mantissa,
long exponentLong) {
if (mantissa == null) {
throw new ArgumentNullException(nameof(mantissa));
}
if (mantissa.CanFitInInt64()) {
long mantissaLong = mantissa.ToInt64Checked();
return Create(mantissaLong, exponentLong);
}
FastIntegerFixed fi = FastIntegerFixed.FromBig(mantissa);
int sign = fi.Sign;
return new EDecimal(
sign < 0 ? fi.Negate() : fi,
FastIntegerFixed.FromInt64(exponentLong),
(byte)((sign < 0) ? BigNumberFlags.FlagNegative : 0));
}
/// <summary>Creates a number with the value
/// <c>exponent*10^significand</c>.</summary>
/// <param name='mantissa'>Desired value for the significand.</param>
/// <param name='exponent'>Desired value for the exponent.</param>
/// <returns>An arbitrary-precision decimal number.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='mantissa'/> or <paramref name='exponent'/> is
/// null.</exception>
public static EDecimal Create(
EInteger mantissa,
EInteger exponent) {
if (mantissa == null) {
throw new ArgumentNullException(nameof(mantissa));
}
if (exponent == null) {
throw new ArgumentNullException(nameof(exponent));
}
if (mantissa.CanFitInInt32() && exponent.IsZero) {
int mantissaSmall = mantissa.ToInt32Checked();
return Create(mantissaSmall, 0);
}
FastIntegerFixed fi = FastIntegerFixed.FromBig(mantissa);
int sign = fi.Sign;
return new EDecimal(
sign < 0 ? fi.Negate() : fi,
FastIntegerFixed.FromBig(exponent),
(byte)((sign < 0) ? BigNumberFlags.FlagNegative : 0));
}
/// <summary>Creates a number with the value
/// <c>exponent*10^significand</c>.</summary>
/// <param name='mantissaLong'>Desired value for the
/// significand.</param>
/// <param name='exponentSmall'>Desired value for the exponent.</param>
/// <returns>An arbitrary-precision decimal number.</returns>
public static EDecimal Create(
long mantissaLong,
int exponentSmall) {
return Create(mantissaLong, (long)exponentSmall);
}
/// <summary>Creates a number with the value
/// <c>exponent*10^significand</c>.</summary>
/// <param name='mantissaLong'>Desired value for the
/// significand.</param>
/// <param name='exponentLong'>Desired value for the exponent.</param>
/// <returns>An arbitrary-precision decimal number.</returns>
public static EDecimal Create(
long mantissaLong,
long exponentLong) {
if (mantissaLong >= Int32.MinValue && mantissaLong <= Int32.MaxValue &&
exponentLong >= Int32.MinValue && exponentLong <= Int32.MaxValue) {
return Create((int)mantissaLong, (int)exponentLong);
} else if (mantissaLong == Int64.MinValue) {
FastIntegerFixed fi = FastIntegerFixed.FromInt64(mantissaLong);
return new EDecimal(
fi.Negate(),
FastIntegerFixed.FromInt64(exponentLong),
(byte)((mantissaLong < 0) ? BigNumberFlags.FlagNegative : 0));
} else {
FastIntegerFixed fi = FastIntegerFixed.FromInt64(Math.Abs(
mantissaLong));
return new EDecimal(
fi,
FastIntegerFixed.FromInt64(exponentLong),
(byte)((mantissaLong < 0) ? BigNumberFlags.FlagNegative : 0));
}
}
/// <summary>Creates a not-a-number arbitrary-precision decimal
/// number.</summary>
/// <param name='diag'>An integer, 0 or greater, to use as diagnostic
/// information associated with this object. If none is needed, should
/// be zero. To get the diagnostic information from another
/// arbitrary-precision decimal floating-point number, use that
/// object's <c>UnsignedMantissa</c> property.</param>
/// <returns>A quiet not-a-number.</returns>
public static EDecimal CreateNaN(EInteger diag) {
return CreateNaN(diag, false, false, null);
}
/// <summary>Creates a not-a-number arbitrary-precision decimal
/// number.</summary>
/// <param name='diag'>An integer, 0 or greater, to use as diagnostic
/// information associated with this object. If none is needed, should
/// be zero. To get the diagnostic information from another
/// arbitrary-precision decimal floating-point number, use that
/// object's <c>UnsignedMantissa</c> property.</param>
/// <param name='signaling'>Whether the return value will be signaling
/// (true) or quiet (false).</param>
/// <param name='negative'>Whether the return value is
/// negative.</param>
/// <param name='ctx'>An arithmetic context to control the precision
/// (in decimal digits) of the diagnostic information. The rounding and
/// exponent range of this context will be ignored. Can be null. The
/// only flag that can be signaled in this context is FlagInvalid,
/// which happens if diagnostic information needs to be truncated and
/// too much memory is required to do so.</param>
/// <returns>An arbitrary-precision decimal number.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='diag'/> is null or is less than 0.</exception>
public static EDecimal CreateNaN(
EInteger diag,
bool signaling,
bool negative,
EContext ctx) {
if (diag == null) {
throw new ArgumentNullException(nameof(diag));
}
if (diag.Sign < 0) {
throw new ArgumentException("Diagnostic information must be 0 or" +
"\u0020greater," + "\u0020 was: " + diag);
}
if (diag.IsZero && !negative) {
return signaling ? SignalingNaN : NaN;
}
var flags = 0;
if (negative) {
flags |= BigNumberFlags.FlagNegative;
}
if (ctx != null && ctx.HasMaxPrecision) {
flags |= BigNumberFlags.FlagQuietNaN;
var ef = new EDecimal(
FastIntegerFixed.FromBig(diag),
FastIntegerFixed.Zero,
(byte)flags).RoundToPrecision(ctx);
int newFlags = ef.flags;
newFlags &= ~BigNumberFlags.FlagQuietNaN;
newFlags |= signaling ? BigNumberFlags.FlagSignalingNaN :
BigNumberFlags.FlagQuietNaN;
return new EDecimal(
ef.unsignedMantissa,
ef.exponent,
(byte)newFlags);
}
flags |= signaling ? BigNumberFlags.FlagSignalingNaN :
BigNumberFlags.FlagQuietNaN;
return new EDecimal(
FastIntegerFixed.FromBig(diag),
FastIntegerFixed.Zero,
(byte)flags);
}
/// <summary>Creates an arbitrary-precision decimal number from a
/// 64-bit binary floating-point number. This method computes the exact
/// value of the floating point number, not an approximation, as is
/// often the case by converting the floating point number to a string
/// first. Remember, though, that the exact value of a 64-bit binary
/// floating-point number is not always the value that results when
/// passing a literal decimal number (for example, calling
/// <c>EDecimal.FromDouble(0.1)</c> ), since not all decimal numbers
/// can be converted to exact binary numbers (in the example given, the
/// resulting arbitrary-precision decimal will be the value of the
/// closest "double" to 0.1, not 0.1 exactly). To create an
/// arbitrary-precision decimal number from a decimal value, use
/// FromString instead in most cases (for example:
/// <c>EDecimal.FromString("0.1")</c> ).</summary>
/// <param name='dbl'>The parameter <paramref name='dbl'/> is a 64-bit
/// floating-point number.</param>
/// <returns>An arbitrary-precision decimal number with the same value
/// as <paramref name='dbl'/>.</returns>
public static EDecimal FromDouble(double dbl) {
long lvalue = BitConverter.ToInt64(
BitConverter.GetBytes((double)dbl),
0);
return FromDoubleBits(lvalue);
}
/// <summary>Creates an arbitrary-precision decimal number from a
/// 64-bit binary floating-point number, encoded in the IEEE 754
/// binary64 format. This method computes the exact value of the
/// floating point number, not an approximation, as is often the case
/// by converting the floating point number to a string first.
/// Remember, though, that the exact value of a 64-bit binary
/// floating-point number is not always the value that results when
/// passing a literal decimal number, since not all decimal numbers can
/// be converted to exact binary numbers (in the example given, the
/// resulting arbitrary-precision decimal will be the value of the
/// closest "double" to 0.1, not 0.1 exactly). To create an
/// arbitrary-precision decimal number from a decimal value, use
/// FromString instead in most cases.</summary>
/// <param name='dblBits'>The parameter <paramref name='dblBits'/> is a
/// 64-bit signed integer.</param>
/// <returns>An arbitrary-precision decimal number with the same value
/// as <paramref name='dblBits'/>.</returns>
public static EDecimal FromDoubleBits(long dblBits) {
var value = new int[] {
unchecked((int)(dblBits & 0xffffffffL)),
unchecked((int)((dblBits >> 32) & 0xffffffffL)),
};
var floatExponent = (int)((value[1] >> 20) & 0x7ff);
bool neg = (value[1] >> 31) != 0;
long lvalue;
if (floatExponent == 2047) {
if ((value[1] & 0xfffff) == 0 && value[0] == 0) {
return neg ? NegativeInfinity : PositiveInfinity;
}
// Treat high bit of mantissa as quiet/signaling bit
bool quiet = (value[1] & 0x80000) != 0;
value[1] &= 0x7ffff;
lvalue = unchecked((value[0] & 0xffffffffL) | ((long)value[1] << 32));
int flags = (neg ? BigNumberFlags.FlagNegative : 0) | (quiet ?
BigNumberFlags.FlagQuietNaN : BigNumberFlags.FlagSignalingNaN);
return lvalue == 0 ? (quiet ? NaN : SignalingNaN) :
new EDecimal(
FastIntegerFixed.FromInt64(lvalue),
FastIntegerFixed.Zero,
(byte)flags);
}
value[1] &= 0xfffff;
// Mask out the exponent and sign
if (floatExponent == 0) {
++floatExponent;
} else {
value[1] |= 0x100000;
}
if ((value[1] | value[0]) != 0) {
floatExponent += NumberUtility.ShiftAwayTrailingZerosTwoElements(
value);
} else {
return neg ? EDecimal.NegativeZero : EDecimal.Zero;
}
floatExponent -= 1075;
lvalue = unchecked((value[0] & 0xffffffffL) | ((long)value[1] << 32));
if (floatExponent == 0) {
if (neg) {
lvalue = -lvalue;
}
return EDecimal.FromInt64(lvalue);
}
if (floatExponent > 0) {
// Value is an integer
var bigmantissa = (EInteger)lvalue;
bigmantissa <<= floatExponent;
if (neg) {
bigmantissa = -(EInteger)bigmantissa;
}
return EDecimal.FromEInteger(bigmantissa);
} else {
// Value has a fractional part
var bigmantissa = (EInteger)lvalue;
EInteger bigexp = NumberUtility.FindPowerOfFive(-floatExponent);
bigmantissa *= (EInteger)bigexp;
if (neg) {
bigmantissa = -(EInteger)bigmantissa;
}
return EDecimal.Create(bigmantissa, (EInteger)floatExponent);
}
}
/// <summary>Converts an arbitrary-precision integer to an arbitrary
/// precision decimal.</summary>
/// <param name='bigint'>An arbitrary-precision integer.</param>
/// <returns>An arbitrary-precision decimal number with the exponent
/// set to 0.</returns>
public static EDecimal FromEInteger(EInteger bigint) {
return EDecimal.Create(bigint, EInteger.Zero);
}
/// <summary>Converts an arbitrary-precision binary floating-point
/// number to an arbitrary precision decimal.</summary>
/// <param name='ef'>An arbitrary-precision binary floating-point
/// number.</param>
/// <returns>An arbitrary-precision decimal number.</returns>
[Obsolete("Renamed to FromEFloat.")]
public static EDecimal FromExtendedFloat(EFloat ef) {
return FromEFloat(ef);
}
/// <summary>Creates an arbitrary-precision decimal number from an
/// arbitrary-precision binary floating-point number.</summary>
/// <param name='bigfloat'>An arbitrary-precision binary floating-point
/// number.</param>
/// <returns>An arbitrary-precision decimal number.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref