-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
decimal.go
1673 lines (1511 loc) · 43.1 KB
/
decimal.go
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 2020 Denis Bernard <[email protected]>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package decimal
import (
"fmt"
"math"
"math/big"
)
const debugDecimal = false // enable for debugging
// DefaultDecimalPrec is the default minimum precision used when creating a new
// Decimal from a *big.Int, *big.Rat, uint64, int64, or string. An uint64
// requires up to 20 digits, which amounts to 2 x 19-digits Words (64 bits) or 3
// x 9-digits Words (32 bits). Forcing the precision to 20 digits would result
// in 18 or 7 unused digits. Using 34 instead gives a higher precision at no
// performance or memory cost on 64 bits platforms (but one more Word on 32
// bits) and gives room for 2 to 4 extra digits of extra precision for internal
// computations at no added performance or memory cost. Also 34 digits matches
// the precision of IEEE-754 decimal128.
const DefaultDecimalPrec = 34
// A nonzero finite Decimal represents a multi-precision decimal floating point
// number
//
// sign × mantissa × 10**exponent
//
// with 0.1 <= mantissa < 1.0, and MinExp <= exponent <= MaxExp. A Decimal may
// also be zero (+0, -0) or infinite (+Inf, -Inf). All Decimals are ordered, and
// the ordering of two Decimals x and y is defined by x.Cmp(y).
//
// Each Decimal value also has a precision, rounding mode, and accuracy. The
// precision is the maximum number of mantissa decimal digits available to
// represent the value. The rounding mode specifies how a result should be
// rounded to fit into the mantissa bits, and accuracy describes the rounding
// error with respect to the exact result.
//
// Unless specified otherwise, all operations (including setters) that specify a
// *Decimal variable for the result (usually via the receiver with the exception
// of MantExp), round the numeric result according to the precision and rounding
// mode of the result variable.
//
// If the provided result precision is 0 (see below), it is set to the precision
// of the argument with the largest precision value before any rounding takes
// place, and the rounding mode remains unchanged. Thus, uninitialized Decimals
// provided as result arguments will have their precision set to a reasonable
// value determined by the operands, and their mode is the zero value for
// RoundingMode (ToNearestEven).
//
// By setting the desired precision to 16 or 34 and using matching rounding mode
// (typically ToNearestEven), Decimal operations produce the same results as the
// corresponding decimal64 or decimal128 IEEE-754 decimal arithmetic for
// operands that correspond to normal (i.e., not subnormal) decimal64 or
// decimal128 numbers. Exponent underflow and overflow lead to a 0 or an
// Infinity for different values than IEEE-754 because Decimal exponents have a
// much larger range.
//
// The zero (uninitialized) value for a Decimal is ready to use and represents
// the number +0.0 exactly, with precision 0 and rounding mode ToNearestEven.
//
// Operations always take pointer arguments (*Decimal) rather than Decimal
// values, and each unique Decimal value requires its own unique *Decimal
// pointer. To "copy" a Decimal value, an existing (or newly allocated) Decimal
// must be set to a new value using the Decimal.Set method; shallow copies of
// Decimals are not supported and may lead to errors.
type Decimal struct {
mant dec
exp int32
prec uint32
mode RoundingMode
acc Accuracy
form form
neg bool
}
// NewDecimal allocates and returns a new Decimal set to x×10**exp, with
// precision DefaultDecimalPrec and rounding mode ToNearestEven.
//
// The result will be set to ±0 if x < 0.1×10**MinPexp, or ±Inf if
// x >= 1×10**MaxExp.
func NewDecimal(x int64, exp int) *Decimal {
u := x
if u < 0 {
u = -u
}
return new(Decimal).setBits64(x < 0, uint64(u), int64(exp))
}
// Abs sets z to the (possibly rounded) value |x| (the absolute value of x)
// and returns z.
func (z *Decimal) Abs(x *Decimal) *Decimal {
z.Set(x)
z.neg = false
return z
}
// Acc returns the accuracy of x produced by the most recent operation.
func (x *Decimal) Acc() Accuracy {
return x.acc
}
// Handling of sign bit as defined by IEEE 754-2008, section 6.3:
//
// When neither the inputs nor result are NaN, the sign of a product or
// quotient is the exclusive OR of the operands’ signs; the sign of a sum,
// or of a difference x−y regarded as a sum x+(−y), differs from at most
// one of the addends’ signs; and the sign of the result of conversions,
// the quantize operation, the roundToIntegral operations, and the
// roundToIntegralExact (see 5.3.1) is the sign of the first or only operand.
// These rules shall apply even when operands or results are zero or infinite.
//
// When the sum of two operands with opposite signs (or the difference of
// two operands with like signs) is exactly zero, the sign of that sum (or
// difference) shall be +0 in all rounding-direction attributes except
// roundTowardNegative; under that attribute, the sign of an exact zero
// sum (or difference) shall be −0. However, x+x = x−(−x) retains the same
// sign as x even when x is zero.
//
// See also: https://play.golang.org/p/RtH3UCt5IH
// Add sets z to the rounded sum x+y and returns z. If z's precision is 0,
// it is changed to the larger of x's or y's precision before the operation.
// Rounding is performed according to z's precision and rounding mode; and
// z's accuracy reports the result error relative to the exact (not rounded)
// result. Add panics with ErrNaN if x and y are infinities with opposite
// signs. The value of z is undefined in that case.
func (z *Decimal) Add(x, y *Decimal) *Decimal {
if debugDecimal {
x.validate()
y.validate()
}
if z.prec == 0 {
z.prec = umax32(x.prec, y.prec)
}
if x.form == finite && y.form == finite {
// x + y (common case)
// Below we set z.neg = x.neg, and when z aliases y this will
// change the y operand's sign. This is fine, because if an
// operand aliases the receiver it'll be overwritten, but we still
// want the original x.neg and y.neg values when we evaluate
// x.neg != y.neg, so we need to save y.neg before setting z.neg.
yneg := y.neg
z.neg = x.neg
if x.neg == yneg {
// x + y == x + y
// (-x) + (-y) == -(x + y)
z.uadd(x, y)
} else {
// x + (-y) == x - y == -(y - x)
// (-x) + y == y - x == -(x - y)
if x.ucmp(y) > 0 {
z.usub(x, y)
} else {
z.neg = !z.neg
z.usub(y, x)
}
}
if z.form == zero && z.mode == ToNegativeInf && z.acc == Exact {
z.neg = true
}
return z
}
if x.form == inf && y.form == inf && x.neg != y.neg {
// +Inf + -Inf
// -Inf + +Inf
// value of z is undefined but make sure it's valid
z.acc = Exact
z.form = zero
z.neg = false
panic(ErrNaN{"addition of infinities with opposite signs"})
}
if x.form == zero && y.form == zero {
// ±0 + ±0
z.acc = Exact
z.form = zero
z.neg = x.neg && y.neg // -0 + -0 == -0
return z
}
if x.form == inf || y.form == zero {
// ±Inf + y
// x + ±0
return z.Set(x)
}
// ±0 + y
// x + ±Inf
return z.Set(y)
}
// z = x + y, ignoring signs of x and y for the addition
// but using the sign of z for rounding the result.
// x and y must have a non-empty mantissa and valid exponent.
func (z *Decimal) uadd(x, y *Decimal) {
// Note: This implementation requires 2 shifts most of the
// time. It is also inefficient if exponents or precisions
// differ by wide margins. The following article describes
// an efficient (but much more complicated) implementation
// compatible with the internal representation used here:
//
// Vincent Lefèvre: "The Generic Multiple-Precision Floating-
// Point Addition With Exact Rounding (as in the MPFR Library)"
// http://www.vinc17.net/research/papers/rnc6.pdf
if debugDecimal {
validateTernaryOperands(z, x, y)
}
// compute exponents ex, ey for mantissa with decimal point
// on the right (mantissa.0) - use int64 to avoid overflow
ex := int64(x.exp) - int64(len(x.mant))*_DW
ey := int64(y.exp) - int64(len(y.mant))*_DW
// TODO(db47h) having a combined add-and-shift primitive
// could make this code significantly faster
// but this needs a version of shl that starts
// from the least significant word and forbids
// in-place shifts.
switch {
case ex < ey:
if same(z.mant, x.mant) {
t := dec(nil).shl(y.mant, uint(ey-ex))
z.mant = z.mant.add(x.mant, t)
} else {
z.mant = z.mant.shl(y.mant, uint(ey-ex))
z.mant = z.mant.add(x.mant, z.mant)
}
default:
// ex == ey, no shift needed
z.mant = z.mant.add(x.mant, y.mant)
case ex > ey:
if same(z.mant, y.mant) {
t := dec(nil).shl(x.mant, uint(ex-ey))
z.mant = z.mant.add(t, y.mant)
} else {
z.mant = z.mant.shl(x.mant, uint(ex-ey))
z.mant = z.mant.add(z.mant, y.mant)
}
ex = ey
}
// len(z.mant) > 0
z.setExpAndRound(ex+int64(len(z.mant))*_DW-dnorm(z.mant), 0)
}
// z = x - y for |x| > |y|, ignoring signs of x and y for the subtraction
// but using the sign of z for rounding the result.
// x and y must have a non-empty mantissa and valid exponent.
func (z *Decimal) usub(x, y *Decimal) {
// This code is symmetric to uadd.
// We have not factored the common code out because
// eventually uadd (and usub) should be optimized
// by special-casing, and the code will diverge.
if debugDecimal {
validateTernaryOperands(z, x, y)
}
ex := int64(x.exp) - int64(len(x.mant))*_DW
ey := int64(y.exp) - int64(len(y.mant))*_DW
switch {
case ex < ey:
if same(z.mant, x.mant) {
t := dec(nil).shl(y.mant, uint(ey-ex))
z.mant = t.sub(x.mant, t)
} else {
z.mant = z.mant.shl(y.mant, uint(ey-ex))
z.mant = z.mant.sub(x.mant, z.mant)
}
default:
// ex == ey, no shift needed
z.mant = z.mant.sub(x.mant, y.mant)
case ex > ey:
if same(z.mant, y.mant) {
t := dec(nil).shl(x.mant, uint(ex-ey))
z.mant = t.sub(t, y.mant)
} else {
z.mant = z.mant.shl(x.mant, uint(ex-ey))
z.mant = z.mant.sub(z.mant, y.mant)
}
ex = ey
}
// operands may have canceled each other out
if len(z.mant) == 0 {
z.acc = Exact
z.form = zero
z.neg = false
return
}
// len(z.mant) > 0
z.setExpAndRound(ex+int64(len(z.mant))*_DW-dnorm(z.mant), 0)
}
// Cmp compares x and y and returns:
//
// -1 if x < y
// 0 if x == y (incl. -0 == 0, -Inf == -Inf, and +Inf == +Inf)
// +1 if x > y
//
func (x *Decimal) Cmp(y *Decimal) int {
if debugDecimal {
x.validate()
y.validate()
}
mx := x.ord()
my := y.ord()
switch {
case mx < my:
return -1
case mx > my:
return +1
}
// mx == my
// only if |mx| == 1 we have to compare the mantissae
switch mx {
case -1:
return y.ucmp(x)
case +1:
return x.ucmp(y)
}
return 0
}
// ord classifies x and returns:
//
// -2 if -Inf == x
// -1 if -Inf < x < 0
// 0 if x == 0 (signed or unsigned)
// +1 if 0 < x < +Inf
// +2 if x == +Inf
//
func (x *Decimal) ord() int {
var m int
switch x.form {
case finite:
m = 1
case zero:
return 0
case inf:
m = 2
}
if x.neg {
m = -m
}
return m
}
// ucmp returns -1, 0, or +1, depending on whether
// |x| < |y|, |x| == |y|, or |x| > |y|.
// x and y must have a non-empty mantissa and valid exponent.
func (x *Decimal) ucmp(y *Decimal) int {
if debugDecimal {
validateBinaryOperands(x, y)
}
switch {
case x.exp < y.exp:
return -1
case x.exp > y.exp:
return +1
}
// x.exp == y.exp
// compare mantissas
i := len(x.mant)
j := len(y.mant)
for i > 0 || j > 0 {
var xm, ym Word
if i > 0 {
i--
xm = x.mant[i]
}
if j > 0 {
j--
ym = y.mant[j]
}
switch {
case xm < ym:
return -1
case xm > ym:
return +1
}
}
return 0
}
// Copy sets z to x, with the same precision, rounding mode, and
// accuracy as x, and returns z. x is not changed even if z and
// x are the same.
func (z *Decimal) Copy(x *Decimal) *Decimal {
if debugDecimal {
x.validate()
}
if z != x {
z.prec = x.prec
z.mode = x.mode
z.acc = x.acc
z.form = x.form
z.neg = x.neg
if z.form == finite {
z.mant = z.mant.set(x.mant)
z.exp = x.exp
}
}
return z
}
// Float sets z to the (possibly rounded) value of x. If a non-nil *big.Float
// argument z is provided, Float stores the result in z instead of allocating a
// new big.Float.
// If z's precision is 0, it is changed to max(⌈x.Prec() * log2(10)⌉, 64).
func (x *Decimal) Float(z *big.Float) *big.Float {
if z == nil {
z = new(big.Float).SetMode(big.RoundingMode(x.mode))
}
p := uint(z.Prec())
if p == 0 {
p = uint(max(int(math.Ceil(float64(x.prec)*log2_10)), 64))
}
// clear z
z.SetPrec(0)
switch x.form {
case zero:
z.SetPrec(p)
if x.neg != z.Signbit() {
z.Neg(z)
}
return z
case inf:
return z.SetInf(x.neg).SetPrec(p)
}
// increase precision
z.SetPrec(p + 1)
// big.Float has no SetBits. Need to use a temp Int.
var i big.Int
i.SetBits(decToNat(nil, x.mant))
m := len(x.mant) * _DW
exp := int64(x.exp) - int64(m)
z = z.SetInt(&i)
if x.neg {
z.Neg(z)
}
// z = x·2**(m - x.exp)·5**(m - x.exp)
// normalize mantissa and apply 2 exponent
// done in two steps since SetMantExponent takes an int.
z.SetMantExp(z, -m) // z = x·2**(-x.exp)·5**(m - x.exp)
z.SetMantExp(z, int(x.exp)) // z = x·5**(m - x.exp)
// now multiply/divide by 5**exp
if exp != 0 {
t := new(big.Float).SetPrec(uint(p))
if exp < 0 {
z.Quo(z, floatPow5(t, uint64(-exp)))
} else {
z.Mul(z, floatPow5(t, uint64(exp)))
}
}
// round
return z.SetPrec(p)
}
// Float32 returns the float32 value nearest to x. If x is too small to be
// represented by a float32 (|x| < math.SmallestNonzeroFloat32), the result
// is (0, Below) or (-0, Above), respectively, depending on the sign of x.
// If x is too large to be represented by a float32 (|x| > math.MaxFloat32),
// the result is (+Inf, Above) or (-Inf, Below), depending on the sign of x.
func (x *Decimal) Float32() (float32, Accuracy) {
z := x.Float(new(big.Float).SetPrec(32))
f, a := z.Float32()
// If big.Float -> float64 conversion is accurate, use Decimal->Float accuracy.
if a == big.Exact {
a = z.Acc()
}
return f, Accuracy(a)
}
// Float64 returns the float64 value nearest to x. If x is too small to be
// represented by a float64 (|x| < math.SmallestNonzeroFloat64), the result
// is (0, Below) or (-0, Above), respectively, depending on the sign of x.
// If x is too large to be represented by a float64 (|x| > math.MaxFloat64),
// the result is (+Inf, Above) or (-Inf, Below), depending on the sign of x.
func (x *Decimal) Float64() (float64, Accuracy) {
z := x.Float(new(big.Float).SetPrec(64))
f, a := z.Float64()
// If big.Float -> float64 conversion is accurate, use Decimal->Float accuracy.
if a == big.Exact {
a = z.Acc()
}
return f, Accuracy(a)
}
// Int returns the result of truncating x towards zero; or nil if x is an
// infinity.
// The result is Exact if x.IsInt(); otherwise it is Below for x > 0, and Above
// for x < 0.
// If a non-nil *Int argument z is provided, Int stores the result in z instead
// of allocating a new Int.
func (x *Decimal) Int(z *big.Int) (*big.Int, Accuracy) {
if debugDecimal {
x.validate()
}
if z == nil && x.form <= finite {
z = new(big.Int)
}
switch x.form {
case finite:
// 0 < |x| < +Inf
acc := makeAcc(x.neg)
if x.exp <= 0 {
// 0 < |x| < 1
return z.SetInt64(0), acc
}
// x.exp > 0
// 1 <= |x| < +Inf
if x.MinPrec() <= uint(x.exp) {
acc = Exact
}
// TODO(db47h): decToNat incurs a copy of its x parameter.
// Here we do not care about trashing it.
z.SetBits(decToNat(z.Bits(), x.intMant()))
if x.neg != (z.Sign() < 0) {
z.Neg(z)
}
return z, acc
case zero:
return z.SetInt64(0), Exact
case inf:
return nil, makeAcc(x.neg)
}
panic("unreachable")
}
// intMant returns the de-normalized integer part of x's mantissa (least significant digit in z[0]).
func (x *Decimal) intMant() dec {
// determine minimum required precision for x
allDigits := uint(len(x.mant)) * _DW
exp := uint(x.exp)
// shift mantissa as needed
var z dec
switch {
case exp > allDigits:
z = z.shl(x.mant, exp-allDigits)
default:
z = z.set(x.mant)
case exp < allDigits:
z = z.shr(x.mant, allDigits-exp)
}
return z
}
// Int64 returns the integer resulting from truncating x towards zero.
// If math.MinInt64 <= x <= math.MaxInt64, the result is Exact if x is
// an integer, and Above (x < 0) or Below (x > 0) otherwise.
// The result is (math.MinInt64, Above) for x < math.MinInt64,
// and (math.MaxInt64, Below) for x > math.MaxInt64.
func (x *Decimal) Int64() (int64, Accuracy) {
if debugDecimal {
x.validate()
}
switch x.form {
case finite:
// 0 < |x| < +Inf
acc := makeAcc(x.neg)
if x.exp <= 0 {
// 0 < |x| < 1
return 0, acc
}
// x.exp > 0
// 1 <= |x| < +Inf
if x.exp <= 20 {
// get low 64 bits of t
if t, ok := x.intMant().toUint64(); ok {
i := int64(t)
if x.neg {
i = -i
}
if x.MinPrec() <= uint(x.exp) {
acc = Exact // not truncated
}
// 0 <= |x| < 1<<63 or x = math.MinInt64
if t&(1<<63) == 0 || (x.neg && t == 1<<63) {
return i, acc
}
}
}
// x too large
if x.neg {
return math.MinInt64, Above
}
return math.MaxInt64, Below
case zero:
return 0, Exact
case inf:
if x.neg {
return math.MinInt64, Above
}
return math.MaxInt64, Below
}
panic("unreachable")
}
// IsInf reports whether x is +Inf or -Inf.
func (x *Decimal) IsInf() bool {
return x.form == inf
}
// IsInt reports whether x is an integer.
// ±Inf values are not integers.
func (x *Decimal) IsInt() bool {
if debugDecimal {
x.validate()
}
// special cases
if x.form != finite {
return x.form == zero
}
// x.form == finite
if x.exp <= 0 {
return false
}
// x.exp > 0
// mant[0:prec] * 10**exp >= 0 || mant[0:mant.MinPrec()]*10**exp >= 0
return x.prec <= uint32(x.exp) || x.MinPrec() <= uint(x.exp)
}
// IsZero reports whether x is +0 or -0.
func (x *Decimal) IsZero() bool {
if debugDecimal {
x.validate()
}
return x.form == 0
}
// MantExp breaks x into its mantissa and exponent components
// and returns the exponent. If a non-nil mant argument is
// provided its value is set to the mantissa of x, with the
// same precision and rounding mode as x. The components
// satisfy x == mant × 10**exp, with 0.1 <= |mant| < 1.0.
// Calling MantExp with a nil argument is an efficient way to
// get the exponent of the receiver.
//
// Special cases are:
//
// ( ±0).MantExp(mant) = 0, with mant set to ±0
// (±Inf).MantExp(mant) = 0, with mant set to ±Inf
//
// x and mant may be the same in which case x is set to its
// mantissa value.
func (x *Decimal) MantExp(mant *Decimal) (exp int) {
if debugDecimal {
x.validate()
}
if x.form == finite {
exp = int(x.exp)
}
if mant != nil {
mant.Copy(x)
if mant.form == finite {
mant.exp = 0
}
}
return
}
// MinPrec returns the minimum precision required to represent x exactly
// (i.e., the smallest prec before x.SetPrec(prec) would start rounding x).
// The result is 0 for |x| == 0 and |x| == Inf.
func (x *Decimal) MinPrec() uint {
if x.form != finite {
return 0
}
return uint(len(x.mant))*_DW - x.mant.trailingZeroDigits()
}
// Mode returns the rounding mode of x.
func (x *Decimal) Mode() RoundingMode {
return x.mode
}
// Mul sets z to the rounded product x*y and returns z.
// Precision, rounding, and accuracy reporting are as for Add.
// Mul panics with ErrNaN if one operand is zero and the other
// operand an infinity. The value of z is undefined in that case.
func (z *Decimal) Mul(x, y *Decimal) *Decimal {
if debugDecimal {
x.validate()
y.validate()
}
if z.prec == 0 {
z.prec = umax32(x.prec, y.prec)
}
z.neg = x.neg != y.neg
if x.form == finite && y.form == finite {
// x * y (common case)
z.umul(x, y)
return z
}
z.acc = Exact
if x.form == zero && y.form == inf || x.form == inf && y.form == zero {
// ±0 * ±Inf
// ±Inf * ±0
// value of z is undefined but make sure it's valid
z.form = zero
z.neg = false
panic(ErrNaN{"multiplication of zero with infinity"})
}
if x.form == inf || y.form == inf {
// ±Inf * y
// x * ±Inf
z.form = inf
return z
}
// ±0 * y
// x * ±0
z.form = zero
return z
}
// FMA sets z to x * y + u, computed with only one rounding. (That is, FMA
// performs the fused multiply-add of x, y, and u.) If z's precision is 0, it is
// changed to the larger of x's, y's, or u's precision before the operation.
// Rounding, and accuracy reporting are as for Add. FMA panics with ErrNaN if
// multiplying zero with an infinity, or if adding two infinities with opposite
// signs. The value of z is undefined in that case.
func (z *Decimal) FMA(x, y, u *Decimal) *Decimal {
if debugDecimal {
x.validate()
y.validate()
u.validate()
}
if z.prec == 0 {
z.prec = umax32(umax32(x.prec, y.prec), u.prec)
}
if u.form == zero {
return z.Mul(x, y)
}
// 0 < |u| <= Inf
// avoid trashing z if u == z
z0 := z
if alias(z.mant, u.mant) {
z0 = new(Decimal)
z0.mode = z.mode
z0.prec = z.prec
}
z0.neg = x.neg != y.neg
if x.form == finite && y.form == finite {
// x * y (common case)
// prevent rounding in umul
prec := z0.prec
z0.prec = MaxPrec
z0.umul(x, y)
// restore precision without rounding
z0.prec = prec
return z.Add(z0, u)
}
if x.form == zero && y.form == inf || x.form == inf && y.form == zero {
// ±0 * ±Inf
// ±Inf * ±0
// value of z is undefined but make sure it's valid
z.acc = Exact
z.form = zero
z.neg = false
panic(ErrNaN{"multiplication of zero with infinity"})
}
if x.form == inf || y.form == inf {
// ±Inf * y + u
// x * ±Inf + u
z0.acc = Exact
z0.form = inf
return z.Add(z0, u)
}
// ±0 * y + u
// x * ±0 + u
return z.Set(u)
}
// Neg sets z to the (possibly rounded) value of x with its sign negated,
// and returns z.
func (z *Decimal) Neg(x *Decimal) *Decimal {
z.Set(x)
z.neg = !z.neg
return z
}
// Prec returns the mantissa precision of x in decimal digits.
// The result may be 0 for |x| == 0 and |x| == Inf.
func (x *Decimal) Prec() uint {
return uint(x.prec)
}
// Quo sets z to the rounded quotient x/y and returns z.
// Precision, rounding, and accuracy reporting are as for Add.
// Quo panics with ErrNaN if both operands are zero or infinities.
// The value of z is undefined in that case.
func (z *Decimal) Quo(x, y *Decimal) *Decimal {
if debugDecimal {
x.validate()
y.validate()
}
if z.prec == 0 {
z.prec = umax32(x.prec, y.prec)
}
z.neg = x.neg != y.neg
if x.form == finite && y.form == finite {
// x / y (common case)
z.uquo(x, y)
return z
}
z.acc = Exact
if x.form == zero && y.form == zero || x.form == inf && y.form == inf {
// ±0 / ±0
// ±Inf / ±Inf
// value of z is undefined but make sure it's valid
z.form = zero
z.neg = false
panic(ErrNaN{"division of zero by zero or infinity by infinity"})
}
if x.form == zero || y.form == inf {
// ±0 / y
// x / ±Inf
z.form = zero
return z
}
// x / ±0
// ±Inf / y
z.form = inf
return z
}
// z = x / y, ignoring signs of x and y for the division
// but using the sign of z for rounding the result.
// x and y must have a non-empty mantissa and valid exponent.
func (z *Decimal) uquo(x, y *Decimal) {
if debugDecimal {
validateBinaryOperands(x, y)
}
// mantissa length in words for desired result precision + 1
// (at least one extra bit so we get the rounding bit after
// the division)
n := int(z.prec/_DW) + 1
// compute adjusted x.mant such that we get enough result precision
xadj := x.mant
if d := n - len(x.mant) + len(y.mant); d > 0 {
// d extra words needed => add d "0 digits" to x
xadj = make(dec, len(x.mant)+d)
copy(xadj[d:], x.mant)
}
// TODO(db47h): If we have too many digits (d < 0), we should be able
// to shorten x for faster division. But we must be extra careful
// with rounding in that case.
// Compute d before division since there may be aliasing of x.mant
// (via xadj) or y.mant with z.mant.
d := len(xadj) - len(y.mant)
// divide
var r dec
z.mant, r = z.mant.div(nil, xadj, y.mant)
e := int64(x.exp) - int64(y.exp) - int64(d-len(z.mant))*_DW
// The result is long enough to include (at least) the rounding bit.
// If there's a non-zero remainder, the corresponding fractional part
// (if it were computed), would have a non-zero sticky bit (if it were
// zero, it couldn't have a non-zero remainder).
var sbit uint
if len(r) > 0 {
sbit = 1
}
z.setExpAndRound(e-dnorm(z.mant), sbit)
}
// Rat returns the rational number corresponding to x;
// or nil if x is an infinity.
// The result is Exact if x is not an Inf.
// If a non-nil *Rat argument z is provided, Rat stores
// the result in z instead of allocating a new Rat.
func (x *Decimal) Rat(z *big.Rat) (*big.Rat, Accuracy) {
if debugDecimal {
x.validate()
}
if z == nil && x.form <= finite {
z = new(big.Rat)
}
switch x.form {
case finite:
// 0 < |x| < +Inf
allDigits := int32(len(x.mant)) * _DW
// clear denominator
z.Denom().SetBits(z.Denom().Bits()[:0])
// build up numerator and denominator
switch {
case x.exp > allDigits:
m := dec(nil).shl(x.mant, uint(x.exp-allDigits))
z.Num().SetBits(decToNat(z.Num().Bits(), m))
// z already in normal form
default:
z.Num().SetBits(decToNat(z.Num().Bits(), x.mant))
// z already in normal form
case x.exp < allDigits:
z.Num().SetBits(decToNat(z.Num().Bits(), x.mant))
t := dec(nil).setUint64(1)
t = t.shl(t, uint(allDigits-x.exp))
// we cannot set z.b directly since z.norm() is not exported.
y := new(big.Rat)
y.Num().SetBits(decToNat(y.Num().Bits(), t))
z = z.Quo(z, y)
}
if x.neg {
z.Neg(z)
}
return z, Exact
case zero:
return z.SetInt64(0), Exact
case inf:
return nil, makeAcc(x.neg)
}
panic("unreachable")
}
// Set sets z to the (possibly rounded) value of x and returns z.
// If z's precision is 0, it is changed to the precision of x
// before setting z (and rounding will have no effect).
// Rounding is performed according to z's precision and rounding
// mode; and z's accuracy reports the result error relative to the
// exact (not rounded) result.
func (z *Decimal) Set(x *Decimal) *Decimal {
if debugDecimal {
x.validate()
}
z.acc = Exact
if z != x {
z.form = x.form
z.neg = x.neg
if x.form == finite {
z.exp = x.exp
// TODO(db47h): optimize copy of mantissa by rounding x to z direcly.
z.mant = z.mant.set(x.mant)
}
if z.prec == 0 {