forked from ericlagergren/decimal
/
decimal.go
1856 lines (1657 loc) · 41.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
package decimal
import (
"bytes"
"encoding/binary"
"fmt"
"math"
"math/big"
"strconv"
"strings"
)
// Precision and scale limits.
const (
MinScale = math.MinInt64 + 1 // smallest allowed scale.
MaxScale = math.MaxInt64 // largest allowed scale.
MinPrec = 0 // smallest allowed precision.
MaxPrec = math.MaxInt64 // maximum allowed precision.
)
// Constant values for ease of use.
var (
Zero = New(0, 0)
One = New(1, 0)
Five = New(5, 0)
Ten = New(10, 0)
)
// Decimal should be packed.
// Currently on (64-bit architectures):
// compact: 8
// scale: 4
// ctx: 4 + 1 (5)
// mantissa: 1 + 24 (4)
// ----------------
// total: 8 + 4 + 5 + 4 = 48 bytes.
// Decimal represents a multi-precision, fixed-point
// decimal number.
//
// Decimal = v * (10 ^ scale)
//
// A positive scale represents the number of digits to the right
// of the radix. A negative scale represents the value of the
// Decimal (at this point an integer) multiplied by the negated
// value of the scale.
//
// A Decimal's precision represents the number of decimal digits
// that should follow the radix after a lossy arithmetic operation.
type Decimal struct {
// If |mantissa| <= math.MaxInt64 then the mantissa
// will be stored in this field.
compact int64
scale int64
ctx Context
mantissa big.Int
}
func NaN() *Decimal {
return &Decimal{scale: overflown}
}
// New returns a new fixed-point decimal.
func New(value int64, scale int64) *Decimal {
if scale == overflown {
panic("decimal.New: scale is too small")
}
return &Decimal{
compact: value,
scale: scale,
}
}
// NewFromString returns a new Decimal from a string representation.
//
// Example:
//
// d1, err := NewFromString("-123.45")
// d2, err := NewFromString(".0001")
//
func NewFromString(value string) (*Decimal, error) {
originalInput := value
var exp int64
// Check if number is using scientific notation.
eIndex := strings.IndexAny(value, "Ee")
if eIndex != -1 {
expInt, err := strconv.ParseInt(value[eIndex+1:], 10, 64)
if expInt == overflown {
panic("decimal.NewFromString: scale is too small")
}
if err != nil {
if e, ok := err.(*strconv.NumError); ok && e.Err == strconv.ErrRange {
return nil, fmt.Errorf("decimal.NewFromString: can't convert %s to decimal: fractional part too long", value)
}
return nil, fmt.Errorf("decimal.NewFromString: can't convert %s to decimal: exponent is not numeric", value)
}
value = value[:eIndex]
exp = int64(-expInt)
}
var intString string
switch parts := strings.Split(value, "."); len(parts) {
case 1:
// There is no decimal point, we can just parse the original string as
// a whole integer
intString = value
case 2:
intString = parts[0] + parts[1]
exp += int64(len(parts[1]))
default:
return nil, fmt.Errorf("decimal.NewFromString: can't convert %s to decimal: too many .s", value)
}
dValue := new(big.Int)
_, ok := dValue.SetString(intString, 10)
if !ok {
return nil, fmt.Errorf("decimal.NewFromString: can't convert %s to decimal", value)
}
if exp < math.MinInt64 || exp > math.MaxInt64 {
// NOTE(vadim): I doubt a string could realistically be this long
return nil, fmt.Errorf("decimal.NewFromString: can't convert %s to decimal: fractional part too long", originalInput)
}
// Determine if we can fit the value into an int64.
// We stuff the value into a big.Int first since it's
// guaranteed to fit and best-case we only parse the
// string once.
//
// TODO(eric): Heuristics to check whether or not we can
// fit the input inside an int64 before we stuff it into
// a big.Int.
z := Decimal{
compact: overflown,
scale: int64(exp),
mantissa: *dValue,
}
return z.Shrink(), nil
}
// NewFromFloat converts a float64 to Decimal.
//
// Keep in mind that float -> decimal conversions can be lossy.
// For example, 0.1 appears to be "just" 0.1, but in reality it's
// 0.1000000000000000055511151231257827021181583404541015625
// (see: fmt.Printf("%.55f", 0.1))
//
// In order to cope with this, the number of decimal digits in the float
// are calculated as closely as possible use that as the scale.
//
// Approximately 2.3% of decimals created from floats will have a rounding
// imprecision of ± 1 ULP.
//
// Example:
//
// NewFromFloat(123.45678901234567).String() // output: "123.4567890123456"
// NewFromFloat(.00000000000000001).String() // output: "0.00000000000000001"
//
// NOTE: this will panic on NaN, +/-inf
func NewFromFloat(value float64) *Decimal {
return NewFromFloatWithScale(value, prec(value))
}
// NewFromFloatWithScale converts a float64 to Decimal, with an arbitrary
// number of fractional digits.
//
// Example:
//
// NewFromFloatWithScale(123.456, 2).String() // output: "123.46"
//
func NewFromFloatWithScale(value float64, scale int64) *Decimal {
if scale == overflown {
panic("decimal: scale is too small")
}
value *= pow10(scale)
if math.IsNaN(value) || math.IsInf(value, 0) {
panic(fmt.Sprintf("decimal: cannot create a Decimal from %v", value))
}
z := Decimal{scale: scale}
// Given float64(math.MaxInt64) == math.MaxInt64
if value <= math.MaxInt64 {
// TODO(eric):
// Should we put an integer that's so close to overflowing inside
// the compact member?
z.compact = int64(value)
} else {
// Given float64(math.MaxUint64) == math.MaxUint64
if value <= math.MaxUint64 {
z.mantissa.SetUint64(uint64(value))
} else {
z.mantissa.Set(bigIntFromFloat(value))
}
z.compact = overflown
}
return &z
}
// "stolen" from https://golang.org/pkg/math/big/#Rat.SetFloat64
// Removed non-finite case because we already check for
// Inf/NaN values
func bigIntFromFloat(f float64) *big.Int {
const expMask = 1<<11 - 1
bits := math.Float64bits(f)
mantissa := bits & (1<<52 - 1)
exp := int((bits >> 52) & expMask)
if exp == 0 { // denormal
exp -= 1022
} else { // normal
mantissa |= 1 << 52
exp -= 1023
}
shift := 52 - exp
// Optimization (?): partially pre-normalise.
for mantissa&1 == 0 && shift > 0 {
mantissa >>= 1
shift--
}
if shift < 0 {
shift = -shift
}
var a big.Int
a.SetUint64(mantissa)
return a.Lsh(&a, uint(shift))
}
// prec determines the precision of a float64.
func prec(f float64) (precision int64) {
if math.IsNaN(f) ||
math.IsInf(f, 0) ||
math.Floor(f) == f {
return 0
}
e := float64(1)
for cmp := round(f*e) / e; !math.IsNaN(cmp) && cmp != f; cmp = round(f*e) / e {
e *= 10
}
return int64(math.Ceil(math.Log10(e)))
}
// Abs sets z to the absolute value of x and returns z.
func (z *Decimal) Abs(x *Decimal) *Decimal {
if x.compact != overflown {
z.compact = abs(x.compact)
} else {
z.mantissa.Abs(&x.mantissa)
z.compact = overflown
}
z.scale = x.scale
return z
}
// Add sets z to x + y and returns z.
func (z *Decimal) Add(x, y *Decimal) *Decimal {
// The Mul method follows the same steps as Adz, so I'll detail the
// formula in the various add methods.
if x.compact != overflown {
if y.compact != overflown {
return z.addCompact(x, y)
}
return z.addHalf(x, y)
}
if y.compact != overflown {
return z.addHalf(y, x)
}
return z.addBig(x, y)
}
// addCompact set d to the sum of x and y and returns z.
// Each case depends on the scales.
func (z *Decimal) addCompact(x, y *Decimal) *Decimal {
// Fast path: we don't need to adjust anything.
// Just check for overflows (if so, use a big.Int)
// and return the result.
if x.scale == y.scale {
z.scale = x.scale
sum := sum(x.compact, y.compact)
if sum != overflown {
z.compact = sum
} else {
z.mantissa.Add(big.NewInt(x.compact), big.NewInt(y.compact))
z.compact = overflown
}
return z
}
// Guess the high and low scale. If we guess wrong, swap.
hi, lo := x, y
if hi.scale < lo.scale {
hi, lo = lo, hi
}
// Find which power of 10 we have to multiply our low value by in order
// to equalize their scales.
inc := safeScale(lo.compact, hi.scale, sub(hi.scale, lo.scale))
z.scale = hi.scale
// Expand the low value (checking for overflows) and
// find the sum (checking for overflows).
//
// If we overflow at all use a big.Int to calculate the sum.
scaledLo := mulPow10(lo.compact, inc)
if scaledLo != overflown {
sum := sum(hi.compact, scaledLo)
if sum != overflown {
z.compact = sum
return z
}
}
scaled := mulBigPow10(big.NewInt(lo.compact), inc)
z.mantissa.Add(scaled, big.NewInt(hi.compact))
z.compact = overflown
return z
}
// addHalf adds a compact Decimal with a non-compact
// Decimal.
// Let the first arg be the compact and the second the non-compact.
func (z *Decimal) addHalf(comp, nc *Decimal) *Decimal {
if comp.compact == overflown {
panic("decimal.Add: (bug) comp should != overflown")
}
if comp.scale == nc.scale {
z.mantissa.Add(big.NewInt(comp.compact), &nc.mantissa)
z.scale = comp.scale
z.compact = overflown
return z
}
// Since we have to rescale we need to add two big.Ints
// together because big.Int doesn't have an API for
// increasing its value by an integer.
return z.addBig(&Decimal{
mantissa: *big.NewInt(comp.compact),
scale: comp.scale,
}, nc)
}
func (z *Decimal) addBig(x, y *Decimal) *Decimal {
hi, lo := x, y
if hi.scale < lo.scale {
hi, lo = lo, hi
}
inc := safeScale(lo.compact, hi.scale, sub(hi.scale, lo.scale))
scaled := mulBigPow10(&lo.mantissa, inc)
z.mantissa.Add(&hi.mantissa, scaled)
z.compact = overflown
z.scale = hi.scale
return z
}
// and sets z to to x & n and returns z.
func (z *Decimal) and(x *Decimal, n int64) *Decimal {
if x.compact != overflown {
z.compact = x.compact & n
} else {
z.mantissa.And(&x.mantissa, big.NewInt(n))
z.compact = overflown
}
return z
}
// Binomial sets z to the binomial coefficient of (n, k) and returns z.
func (z *Decimal) Binomial(n, k int64) *Decimal {
if n/2 < k && k <= n {
k = n - k
}
var a, b Decimal
a.MulRange(n-k+1, n)
b.MulRange(1, k)
return z.Div(&a, &b)
}
// BitLen returns the absolute value of z in bits.
func (z *Decimal) BitLen() int64 {
if z.compact != overflown {
x := z.compact
if z.scale < 0 {
x = mulPow10(x, -z.scale)
}
if x != overflown {
return (64 - clz(x))
}
}
x := &z.mantissa
if z.scale < 0 {
// Double check because we fall through if
// mulPow10(x, -z.scale) returns overflown.
if z.compact != overflown {
x = mulBigPow10(big.NewInt(z.compact), -z.scale)
} else {
x = mulBigPow10(x, -z.scale)
}
}
return int64(x.BitLen())
}
// Bytes returns the absolute value of z as a big-endian
// byte slice.
func (z *Decimal) Bytes() []byte {
if z.compact != overflown {
var b [8]byte
binary.BigEndian.PutUint64(b[:], uint64(abs(z.compact)))
return b[:]
}
return z.mantissa.Bytes()
}
// Ceil sets z to the nearest integer value greater than or equal to x
// and returns z.
func (z *Decimal) Ceil(x *Decimal) *Decimal {
z.Floor(z.Neg(x))
return z.Neg(z)
}
// Cmp compares d and x and returns:
//
// -1 if z < x
// 0 if z == x
// +1 if z > x
//
// It does not modify d or x.
func (z *Decimal) Cmp(x *Decimal) int {
// Check for same pointers.
if z == x {
return 0
}
// Same scales means we can compare straight across.
if z.scale == x.scale &&
z.compact != overflown && x.compact != overflown {
if z.compact > x.compact {
return +1
}
if z.compact < x.compact {
return -1
}
return 0
}
// Different scales -- check signs and/or if they're
// both zero.
ds := z.Sign()
xs := x.Sign()
switch {
case ds > xs:
return +1
case ds < xs:
return -1
case ds == 0 && xs == 0:
return 0
}
// Scales aren't equal, the signs are the same, and both
// are non-zero.
dl := z.Ilog10() - z.scale
xl := x.Ilog10() - x.scale
if dl > xl {
return +1
}
if dl < xl {
return -1
}
// We need to inflate one of the numbers.
dc := z.compact // hi
xc := x.compact // lo
var swap bool
hi, lo := z, x
if hi.scale < lo.scale {
hi, lo = lo, hi
dc, xc = xc, dc
swap = true // d is lo
}
diff := hi.scale - lo.scale
if diff <= math.MaxInt64 {
xc = mulPow10(xc, diff)
if xc == overflown && dc == overflown {
// d is lo
if swap {
return mulBigPow10(&z.mantissa, diff).
Cmp(&x.mantissa)
}
// x is lo
return z.mantissa.Cmp(mulBigPow10(&x.mantissa, diff))
}
}
if swap {
dc, xc = xc, dc
}
if dc != overflown {
if xc != overflown {
return cmpAbs(dc, xc)
}
return big.NewInt(dc).Cmp(&x.mantissa)
}
if xc != overflown {
return z.mantissa.Cmp(big.NewInt(xc))
}
return z.mantissa.Cmp(&x.mantissa)
}
// Dim sets z to the maximum of x - y or 0 and returns z.
func (z *Decimal) Dim(x, y *Decimal) *Decimal {
x0 := new(Decimal).Sub(x, y)
return Max(x0, New(0, 0))
}
// DivMod sets z to the quotient x div y and m to the modulus x mod y and
// returns the pair (z, m) for y != 0. If y == 0, a division-by-zero run-time panic occurs
func (z *Decimal) DivMod(x, y, m *Decimal) (div *Decimal, moz *Decimal) {
if y.ez() {
panic("decimal.DivMod: division by zero")
}
if x.ez() {
z.compact = 0
z.scale = safeScale2(x.scale, sub(x.scale, y.scale))
return z, m.SetInt64(0)
}
if x.compact != overflown {
if y.compact != overflown {
if m.compact != overflown {
return z.divCompact(x, y, m)
}
return z.divBig(x, y, &Decimal{
mantissa: *big.NewInt(m.compact),
scale: m.scale,
})
}
return z.divBig(&Decimal{
mantissa: *big.NewInt(x.compact),
scale: x.scale,
}, y, m)
}
if y.compact != overflown {
return z.divBig(x, &Decimal{
mantissa: *big.NewInt(y.compact),
scale: y.scale,
}, m)
}
return z.divBig(x, y, m)
}
// Div sets z to the quotient x/y for y != 0 and returns z. If y == 0, a
// division-by-zero run-time panic occurs.
func (z *Decimal) Div(x, y *Decimal) *Decimal {
var r Decimal
div, _ := z.DivMod(x, y, &r)
return div
}
func (z *Decimal) needsInc(x, r int64, pos, odd bool) bool {
m := 1
if r > math.MinInt64/2 || r <= math.MaxInt64/2 {
m = cmpAbs(r<<1, x)
}
return z.ctx.Mode.needsInc(m, pos, odd)
}
func (z *Decimal) needsIncBig(x, r *big.Int, pos, odd bool) bool {
var x0 big.Int
m := cmpBigAbs(*x0.Mul(r, twoInt), *x)
return z.ctx.Mode.needsInc(m, pos, odd)
}
func (z *Decimal) divCompact(x, y, m *Decimal) (div *Decimal, moz *Decimal) {
shift := z.Prec()
// Shifts >= 19 are guaranteed to overflow.
if shift < 19 {
// We're still not guaranteed to not overflow.
x0 := prod(x.compact, pow10int64(shift))
if x0 != overflown {
q := x0 / y.compact
r := x0 % y.compact
sign := int64(1)
if (x.compact < 0) != (y.compact < 0) {
sign = -1
}
z.compact = q
if r != 0 && z.needsInc(y.compact, r, sign > 0, q&1 != 0) {
z.compact += sign
}
z.scale = safeScale2(x.scale, x.scale-y.scale+shift)
return z.SetPrec(shift), m.SetInt64(r)
}
}
return z.divBig(
&Decimal{
mantissa: *big.NewInt(x.compact),
scale: x.scale,
},
&Decimal{
mantissa: *big.NewInt(y.compact),
scale: y.scale,
},
&Decimal{
mantissa: *big.NewInt(m.compact),
scale: m.scale,
},
)
}
func (z *Decimal) divBig(x, y, m *Decimal) (div *Decimal, moz *Decimal) {
shift := z.Prec()
x0 := mulBigPow10(&x.mantissa, shift)
q, r := x0.DivMod(x0, &y.mantissa, &m.mantissa)
sign := int64(1)
if (x.mantissa.Sign() < 0) && (y.mantissa.Sign() < 0) {
sign = -1
}
z.mantissa = *q
m.mantissa = *r
odd := new(big.Int).And(q, oneInt).Cmp(zeroInt) != 0
if r.Cmp(zeroInt) != 0 && z.needsIncBig(&y.mantissa, r, sign > 0, odd) {
z.mantissa.Add(&z.mantissa, big.NewInt(sign))
}
z.scale = safeScale2(x.scale, x.scale-y.scale+shift)
z.compact = overflown
m.compact = overflown
// I'm only comfortable calling shrink here because division
// has a tendency to blow up numbers real big and then
// shrink them back down.
return z.Shrink().SetPrec(shift), m.Shrink()
}
// Equals returns true if z == x.
func (z *Decimal) Equals(x *Decimal) bool {
return z.Cmp(x) == 0
}
// The following are some internal optimizations when we need to compare a
// Decimal to zero since d's comparison methods aren't optimized for 'zero'.
// ez returns true if z == 0.
func (z *Decimal) ez() bool {
return z.Sign() == 0
}
// ltz returns true if z < 0
func (z *Decimal) ltz() bool {
return z.Sign() < 0
}
// ltez returns true if z <= 0
func (z *Decimal) ltez() bool {
return z.Sign() <= 0
}
// gtz returns true if z > 0
func (z *Decimal) gtz() bool {
return z.Sign() > 0
}
// gtez returns true if z >= 0
func (z *Decimal) gtez() bool {
return z.Sign() >= 0
}
// Exp sets z to x**y mod |m| and returns z.
//
// If m == nil or m == 0, z == z**y.
// If y <= the result is 1 mod |m|.
//
// Special cases are (in order):
//
// Exp(x, ±0) = 1 for any x
// Exp(1, y) = 1 for any y
// Exp(x, 1) = x for any x
// Exp(NaN, y) = NaN
// Exp(x, NaN) = NaN
// Exp(±0, y) = ±Inf for y an odd integer < 0
// Exp(±0, -Inf) = +Inf
// Exp(±0, +Inf) = +0
// Exp(±0, y) = +Inf for finite y < 0 and not an odd integer
// Exp(±0, y) = ±0 for y an odd integer > 0
// Exp(±0, y) = +0 for finite y > 0 and not an odd integer
// Exp(-1, ±Inf) = 1
// Exp(x, +Inf) = +Inf for |x| > 1
// Exp(x, -Inf) = +0 for |x| > 1
// Exp(x, +Inf) = +0 for |x| < 1
// Exp(x, -Inf) = +Inf for |x| < 1
// Exp(+Inf, y) = +Inf for y > 0
// Exp(+Inf, y) = +0 for y < 0
// Exp(-Inf, y) = Exp(-0, -y)
// Exp(x, y) = NaN for finite x < 0 and finite non-integer y
func (z *Decimal) Exp(x, y, m *Decimal) *Decimal {
if m == nil {
m = new(Decimal)
}
switch {
case y.ez() || x.Equals(one):
return z.SetInt64(1)
case y.Equals(one):
return z.Set(x)
case y.Equals(ptFive) && m.ez():
return z.Sqrt(x)
}
xbig := x.compact == overflown
ybig := y.compact == overflown
mbig := m.compact == overflown
if !(xbig || ybig || mbig) {
scale := prod(x.scale, y.compact)
if scale == overflown {
return NaN()
}
// If y is an int compute it by squaring (O log n).
// Otherwise, use exp(log(x) * y).
if y.IsInt() {
z.pow(x, y)
} else {
x0 := new(Decimal).Set(x)
neg := x0.ltz()
if neg {
x0.Neg(x0)
}
x0.Log(x0).Mul(x0, y)
z.exp(x0)
if neg {
z.Neg(z)
}
}
if !m.ez() {
m.Mod(z, m)
}
return z
}
// Slow path. Should optimize this.
x0 := &x.mantissa
y0 := &y.mantissa
m0 := &m.mantissa
// If we have any compact Decimals assign those values.
if !xbig {
x0 = new(big.Int).SetInt64(x.compact)
}
if !ybig {
y0 = new(big.Int).SetInt64(y.compact)
}
if !mbig {
m0 = new(big.Int).SetInt64(m.compact)
}
// If y can't fit into an int64 then we'll overflow.
if y0.Cmp(maxInt64) > 0 {
return NaN()
}
// y <= 9223372036854775807
intY := y0.Int64()
// Check for scale overflow.
scale := prod(x.scale, intY)
if scale == overflown {
return nil
}
z.mantissa.Exp(x0, y0, m0)
z.scale = scale
z.compact = overflown
return z
}
// FizzBuzz literally prints out FizzBuzz from 1 up to x.
// No, really. Try it. It works.
// Yes, this is a completely useless function.
func FizzBuzz(x *Decimal) {
var tmp Decimal
fifteen, five, three := New(15, 0), New(5, 0), New(3, 0)
for x0 := New(1, 0); x0.LessThan(x); x0.Add(x0, one) {
switch {
case tmp.Rem(x0, fifteen).ez():
fmt.Println("FizzBuzz")
case tmp.Rem(x0, five).ez():
fmt.Println("Fizz")
case tmp.Rem(x0, three).ez():
fmt.Println("Buzz")
default:
fmt.Println(x0)
}
}
}
// Fib sets z to the Fibonacci number x and returns z.
func (z *Decimal) Fib(x *Decimal) *Decimal {
if x.LessThan(two) {
return z.Set(x)
}
a, b, x0 := New(0, 0), New(1, 0), new(Decimal).Set(x)
for x0.Sub(x0, one); x0.gtz(); x0.Sub(x0, one) {
a.Add(a, b)
a, b = b, a
}
*z = *b
return z
}
// Float64 returns the nearest float64 value for d and a bool indicating
// whether f represents d exactly.
// For more details, see the documentation for big.Rat.Float64
func (z *Decimal) Float64() (f float64, exact bool) {
return z.Rat(nil).Float64()
}
// Floor sets z to the nearest integer value less than or equal to x
// and returns z.
func (z *Decimal) Floor(x *Decimal) *Decimal {
if x.compact != overflown {
if x.compact == 0 {
z.compact = 0
z.scale = 0
return z
}
if x.compact < 0 {
dec, frac := modi(-x.compact, x.scale)
if frac != 0 {
dec++
}
if dec-1 != overflown {
z.compact = -dec
z.scale = 0
return z
}
} else {
dec, _ := modi(x.compact, x.scale)
if dec != overflown {
z.compact = dec
z.scale = 0
return z
}
}
// If we reach here then we can't find the floor without using
// big.Ints to do the math for us.
d0 := new(Decimal).Set(x)
d0.mantissa = *big.NewInt(x.compact)
d0.compact = overflown
return z.Floor(d0)
}
if cmp := x.mantissa.Cmp(zeroInt); cmp == 0 {
z.mantissa.Set(zeroInt)
} else if cmp < 0 {
neg := new(big.Int).Neg(&x.mantissa)
dec, frac := modbig(neg, x.scale)
if frac.Cmp(zeroInt) != 0 {
dec.Add(dec, oneInt)
}
z.mantissa.Set(dec.Neg(dec))
} else {
dec, _ := modbig(&x.mantissa, x.scale)
z.mantissa.Set(dec)
}
z.compact = overflown
z.scale = 0
return z
}
// GreaterThan returns true if d is greater than x.
func (z *Decimal) GreaterThan(x *Decimal) bool {
return z.Cmp(x) > 0
}
// GreaterThanEQ returns true if d is greater than or equal to x.
func (z *Decimal) GreaterThanEQ(x *Decimal) bool {
return z.Cmp(x) >= 0
}
// Hypot sets z to Sqrt(p*p + q*q) and returns z.
func (z *Decimal) Hypot(p, q *Decimal) *Decimal {
p0 := new(Decimal).Set(p)
q0 := new(Decimal).Set(q)
if p0.ltz() {
p0.Neg(p0)
}
if q0.ltz() {
q0.Neg(q0)
}
if p0.ez() {
return New(0, 0)
}
p0.Mul(p0, p0)
q0.Mul(q0, q0)
z.Sqrt(p0.Add(p0, q0))
return z.SetPrec(z.Prec())
}
// Int returns the integer component of z as a big.Int.
func (z *Decimal) Int() *big.Int {
var x big.Int
if z.scale <= 0 {
if z.compact != overflown {
x.SetInt64(z.compact)
} else {
x = z.mantissa
}
return mulBigPow10(&x, -z.scale)
}
if z.compact != overflown {
x.SetInt64(z.compact)
} else {
x.Set(&z.mantissa)
}
b := bigPow10(z.scale)
return x.Div(&x, &b)
}
// Int64 returns the integer component of z as an int64.
// If the integer component cannot fit into an int64 the result is undefined.
func (z *Decimal) Int64() int64 {
var x int64
if z.compact != overflown {
x = z.compact
} else {
x = z.mantissa.Int64()
}
if z.scale <= 0 {
return mulPow10(x, -z.scale)
}
pow := pow10int64(z.scale)
if pow == overflown {
return overflown
}
return x / pow
}
// IsBig returns true if d is too large to fit into its
// integer member and can only be represented by a big.Int.
// (This means that a call to Int will result in undefined
// behavior.)
func (z *Decimal) IsBig() bool {
return z.compact == overflown
}
// IsInt returns true if d can be represented exactly as an integer.
// (This means that the fractional part of the number is zero or the scale
// is <= 0.)
func (z *Decimal) IsInt() bool {
if z.scale <= 0 {
return true
}
_, frac := Modf(z)
return frac.ez()
}
func IsNan(x *Decimal) bool {
return x.scale == overflown
}
// Jacobi returns the Jacobi symbol (x/y), either +1, -1, or 0.
// Both x and y arguments must be integers (i.e., scale <= zero).
// The y argument must be an odd integer.
func Jacobi(x, y *Decimal) int {
if x.scale > 0 || y.scale > 0 {
panic("decimal: invalid arguments to decimal.Jacobi: Jacobi requires integer values")
}