forked from ericlagergren/decimal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
big_ctx.go
3193 lines (2849 loc) · 71.3 KB
/
big_ctx.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 (
"math"
"math/big"
"math/bits"
"github.com/ericlagergren/decimal/internal/arith"
cst "github.com/ericlagergren/decimal/internal/c"
)
// Abs sets z to the absolute value of x and returns z.
func (c Context) Abs(z, x *Big) *Big {
if debug {
x.validate()
}
if !z.invalidContext(z.Context) && !z.checkNaNs(x, x, absvalue) {
c.finish(z.copyAbs(x))
}
return z
}
// Add sets z to x + y and returns z.
func (c Context) Add(z, x, y *Big) *Big {
if debug {
x.validate()
y.validate()
}
if z.invalidContext(c) {
return z
}
if x.IsFinite() && y.IsFinite() {
z.form = c.add(z, x, x.form, y, y.form)
return c.finish(z)
}
// NaN + NaN
// NaN + y
// x + NaN
if z.checkNaNs(x, y, addition) {
return z
}
if x.form&inf != 0 {
if y.form&inf != 0 && x.form^y.form == signbit {
// +Inf + -Inf
// -Inf + +Inf
return z.setNaN(InvalidOperation, qnan, addinfinf)
}
// ±Inf + y
// +Inf + +Inf
// -Inf + -Inf
return c.Set(z, x)
}
// x + ±Inf
return c.Set(z, y)
}
// add sets z to x + y, where x and y are both finite.
//
// The (*Big).form fields are ignored and must be provided as
// separate arguments in order to facilitate Context.Sub.
func (c Context) add(z, x *Big, xform form, y *Big, yform form) form {
// addCompact, addMixed, and addBig all require X be the
// "shifted" number, which means X must have the greater
// exponent.
hi, lo := x, y
hisign, losign := xform, yform
if hi.exp < lo.exp {
hi, lo = lo, hi
hisign, losign = losign, hisign
}
if sign, ok := c.tryTinyAdd(z, hi, hisign, lo, losign); ok {
return sign
}
var sign form
if hi.isCompact() {
if lo.isCompact() {
sign = c.addCompact(z, hi.compact, hisign, lo.compact, losign, uint64(hi.exp-lo.exp))
} else {
sign = c.addMixed(z, &lo.unscaled, losign, lo.exp, hi.compact, hisign, hi.exp)
}
} else if lo.isCompact() {
sign = c.addMixed(z, &hi.unscaled, hisign, hi.exp, lo.compact, losign, lo.exp)
} else {
sign = c.addBig(z, &hi.unscaled, hisign, &lo.unscaled, losign, uint64(hi.exp-lo.exp))
}
z.exp = lo.exp
return sign
}
// tryTinyAdd attempts to set z to X + Y, but only if the
// addition requires such a large shift that the result of the
// addition would be the same if Y were replaced with a smaller
// value.
//
// For example, given
//
// X = 5 * 10^0 // 5
// Y = 3 * 10^-99999 // 3e-99999
//
// X would have to be shifted (multiplied) by
//
// shift = 10 ^ (0 - (-99999)) =
// 10 ^ (0 + 99999) =
// 10^99999
//
// which is a *large* number.
//
// If the desired precision for the addition is 16, the end
// result will be
// rounded down to
//
// 5.0000000000000000
//
// making the shift entirely useless.
//
// Instead, Y can be replaced with a smaller number that rounds
// down to the same result and avoids large shifts.
//
// tryTinyAdd reports whether the "tiny" addition was performed.
func (c Context) tryTinyAdd(z *Big, X *Big, Xsign form, Y *Big, Ysign form) (form, bool) {
if X.isZero() {
return 0, false
}
exp := X.exp - 1
if xp, zp := X.Precision(), c.precision(); xp <= zp {
exp += xp - zp - 1
}
if Y.adjusted() >= exp {
return 0, false
}
var tiny uint64
if Y.compact != 0 {
tiny = 1
}
var sign form
if X.isCompact() {
sign = c.addCompact(z, X.compact, Xsign, tiny, Ysign, uint64(X.exp-exp))
} else {
sign = c.addMixed(z, &X.unscaled, Xsign, X.exp, tiny, Ysign, exp)
}
z.exp = exp
return sign, true
}
// addCompact sets z to X + Y where
//
// X = X0 * 10^shift
//
// and returns the resulting signbit.
func (c Context) addCompact(z *Big, X0 uint64, Xsign form, Y uint64, Ysign form, shift uint64) form {
// Test whether X0 * 10^shift fits inside a uint64. If not,
// fall back to big.Ints.
X, ok := arith.MulPow10(X0, shift)
if !ok {
X0 := z.unscaled.SetUint64(X0)
X := arith.MulBigPow10(X0, X0, shift)
// Because hi was promoted to a big.Int, it by definition
// is larger than lo.
//
// Therefore, the resulting signbit is the same as hi's
// signbit.
//
// Furthermore, we do not need to check if the result of
// the operation is zero.
if Xsign == Ysign {
z.precision = arith.BigLength(arith.Add(&z.unscaled, X, Y))
z.compact = cst.Inflated
} else {
arith.Sub(&z.unscaled, X, Y)
z.norm()
}
return Xsign
}
// If the signs are the same, then X + Y = ℤ≠0.
if Ysign == Xsign {
if sum, c := bits.Add64(X, Y, 0); c == 0 {
z.compact = sum
if sum == cst.Inflated {
z.unscaled.SetUint64(cst.Inflated)
}
z.precision = arith.Length(z.compact)
} else {
arith.Set(&z.unscaled, c, sum)
z.precision = 20
z.compact = cst.Inflated
}
return Xsign
}
sign := Xsign
// X + (-Y) == X - Y == -(Y - X)
// (-X) + Y == Y - X == -(X - Y)
diff, b := bits.Sub64(X, Y, 0)
if b != 0 {
sign ^= signbit
diff = Y - X
}
if diff != 0 {
z.compact = diff
z.precision = arith.Length(z.compact)
return sign
}
sign = 0
// On a zero result:
//
// Otherwise, the sign of a zero result is 0 unless either
// both operands were negative or the signs of the
// operands were different and the rounding is
// round-floor.
//
// http://speleotrove.com/decimal/daops.html#refaddsub
if c.RoundingMode == ToNegativeInf {
sign = Xsign ^ Ysign // either 0 or 1
}
sign |= Xsign & Ysign
z.compact = 0
z.precision = 1
return sign
}
// addMixed sets z to X + Y where
//
// X = X * 10^shift
//
// and returns the resulting signbit.
func (c Context) addMixed(z *Big, X *big.Int, Xform form, xs int, Y uint64, Yform form, ys int) form {
if xs < ys {
shift := uint64(ys - xs)
Y0, ok := arith.MulPow10(Y, shift)
if !ok {
yb := alias(&z.unscaled, X).SetUint64(Y)
yb = arith.MulBigPow10(yb, yb, shift)
return c.addBig(z, X, Xform, yb, Yform, 0)
}
Y = Y0
} else if xs > ys {
X = arith.MulBigPow10(&z.unscaled, X, uint64(xs-ys))
}
if Xform == Yform {
arith.Add(&z.unscaled, X, Y)
z.precision = arith.BigLength(&z.unscaled)
z.compact = cst.Inflated
} else {
// X > Y
arith.Sub(&z.unscaled, X, Y)
z.norm()
}
return Xform
}
// addBig sets z to X + Y where
//
// X = X0 * 10^shift
//
// and returns the resulting signbit.
func (c Context) addBig(z *Big, X *big.Int, Xsign form, Y *big.Int, Ysign form, shift uint64) form {
// Guard the call so we don't allocate (via alias) if we don't need to.
if shift != 0 {
X = arith.MulBigPow10(alias(&z.unscaled, Y), X, shift)
}
if Xsign == Ysign {
z.unscaled.Add(X, Y)
z.compact = cst.Inflated
z.precision = arith.BigLength(&z.unscaled)
return Xsign
}
sign := Xsign
// X + (-Y) == X - Y == -(Y - X)
// (-X) + Y == Y - X == -(X - Y)
if X.Cmp(Y) >= 0 {
z.unscaled.Sub(X, Y)
} else {
sign ^= signbit
z.unscaled.Sub(Y, X)
}
if z.unscaled.Sign() == 0 {
z.compact = 0
z.precision = 1
sign = 0
if c.RoundingMode == ToNegativeInf {
sign = Xsign ^ Ysign // either 0 or 1
}
return sign | Xsign&Ysign
}
z.norm()
return sign
}
// Acos returns the arccosine, in radians, of x.
//
// Range:
// Input: -1 <= x <= 1
// Output: 0 <= Acos(x) <= pi
//
// Special cases:
// Acos(NaN) = NaN
// Acos(±Inf) = NaN
// Acos(x) = NaN if x < -1 or x > 1
// Acos(-1) = pi
// Acos(1) = 0
func (c Context) Acos(z, x *Big) *Big {
if debug {
x.validate()
}
if z.invalidContext(c) {
return z
}
if z.checkNaNs(x, x, acos) {
return z
}
cmp1 := cmpAbsInt(x, 1)
if x.IsInf(0) || cmp1 > 0 {
z.Context.Conditions |= InvalidOperation
return z.SetNaN(false)
}
if cmp1 == 0 {
if x.Signbit() {
return c.pi(z)
}
return z.SetUint64(0)
}
ctx := c.dup()
ctx.Precision += defaultExtraPrecision
// Acos(x) = pi/2 - arcsin(x)
pi2 := ctx.pi2(getDec(ctx))
ctx.Sub(z, pi2, ctx.Asin(z, x))
putDec(pi2)
return c.finish(z)
}
// Asin returns the arcsine, in radians, of x.
//
// Range:
// Input: -1 <= x <= 1
// Output: -pi/2 <= Asin(x) <= pi/2
//
// Special cases:
// Asin(NaN) = NaN
// Asin(±Inf) = NaN
// Asin(x) = NaN if x < -1 or x > 1
// Asin(±1) = ±pi/2
func (c Context) Asin(z, x *Big) *Big {
if debug {
x.validate()
}
if z.invalidContext(c) {
return z
}
if z.checkNaNs(x, x, asin) {
return z
}
cmp1 := cmpAbsInt(x, 1)
if x.IsInf(0) || cmp1 > 0 {
z.Context.Conditions |= InvalidOperation
return z.SetNaN(false)
}
if cmp1 == 0 {
c.pi2(z)
if x.Signbit() {
z.SetSignbit(true)
}
return z
}
ctx := c.dup()
ctx.Precision += defaultExtraPrecision
// Asin(x) = 2 * atan(x / (1 + sqrt(1 - x*x)))
if z == x {
x = getDec(c).Copy(x)
defer putDec(x)
}
c.Mul(z, x, x) // x*x
ctx.Sub(z, one.get(), z) // 1 - x*x
ctx.Sqrt(z, z) // sqrt(1 - x*x)
ctx.Add(z, one.get(), z) // 1 + sqrt(1 - x*x)
ctx.Quo(z, x, z) // x / (1 + sqrt(1 - x*x))
ctx.Atan(z, z) // atan(x / (1 + sqrt(1 - x*x)))
ctx.Mul(z, z, two.get()) // 2 * atan(x / (1 + sqrt(1 - x*x)))
return c.finish(z)
}
// Atan returns the arctangent, in radians, of x.
//
// Range:
// Input: all real numbers
// Output: -pi/2 <= Atan(x) <= pi/2
//
// Special cases:
// Atan(NaN) = NaN
// Atan(±Inf) = ±x * pi/2
func (c Context) Atan(z, x *Big) *Big {
if debug {
x.validate()
}
if z.invalidContext(c) {
return z
}
if z.checkNaNs(x, x, atan) {
return z
}
if x.IsInf(0) {
c.pi2(z)
z.form |= x.form & signbit
return z
}
ctx := c.dup()
ctx.Precision += defaultExtraPrecision
// when x <-1 we use -atan(-x) instead
if cmpInt(x, -1) < 0 {
z.CopyNeg(x) // -x
ctx.Atan(z, z) // atan(-x)
return c.Neg(z, z) // -atan(-x)
}
y, ySq, ySqPlus1, segment, halved := ctx.prepAtan(z, x) // z == y, maybe.
result := BinarySplitDynamic(c,
func(_ uint64) *Big { return y },
ctx.getAtanP(ySq),
func(_ uint64) *Big { return one.get() },
ctx.getAtanQ(ySqPlus1),
)
// undo the double angle part
tmp := ctx.Pow(ySq, two.get(), z.SetMantScale(int64(halved), 0)) // clobber ySq
ctx.Mul(z, result, tmp)
// to handle the argument reduction step
// check which segment the value was from
// seg 0: 0 < value <= sqrt(3)/3 // then result = result
// seg 1: sqrt(3)/3 < value <= 1 // then result = pi/6 + result
// set 2: 1 < value // then result = pi/2 - result
switch segment {
case 1:
piOver6 := c.pi(tmp) // clobber _2p
ctx.Quo(piOver6, piOver6, six.get())
ctx.Add(z, piOver6, z)
case 2:
ctx.Sub(z, ctx.pi2(tmp), z) // clobber _2p
}
return c.finish(z)
}
var sqrt3_3 = New(577350, 6) // sqrt(3) / 3
func (c Context) prepAtan(z, x *Big) (y, ySq, ySqPlus1 *Big, segment, halved int) {
c.Precision += defaultExtraPrecision
if x == z {
x = getDec(c).Copy(x)
defer putDec(x)
}
// since smaller values converge faster
// we'll use argument reduction
// if |x| > 1 then set x = 1/x
segment = 0
switch {
case cmpAbsInt(x, 1) > 0:
segment = 2
c.Quo(z, one.get(), x)
case x.CmpAbs(sqrt3_3) > 0:
// if |x| > sqrt(3)/3 (approximated to 0.577350)
segment = 1
// then set x = (sqrt(3)*x-1)/(sqrt(3)+x)
sqrt3 := c.sqrt3(new(Big))
c.Mul(z, sqrt3, x) // sqrt(3) * x
c.Sub(z, z, one.get()) // sqrt(3)*x - 1
c.Add(sqrt3, sqrt3, x) // sqrt(3) + x
c.Quo(z, z, sqrt3) // (sqrt(3)*x - 1) / (sqrt(3) + x)
default:
z.Copy(x)
}
// next we'll use argument halving technic
// atan(y) = 2 atan(y/(1+sqrt(1+y^2)))
// we'll repeat this up to a point
// we have competing operations at some
// point the sqrt causes a problem
// note (http://fredrikj.net/blog/2014/12/faster-high-ctx-Atangents/)
// suggests that r= 8 times is a good value for
// precision with 1000s of digits to millions
// however it was easy to determine there is a
// better sliding window to use instead
// which is what we use as it turns out
// when the ctx is large, a larger r value
// compared to 8 is every effective
xf, _ := z.Float64()
xf = math.Abs(xf)
// the formula simple but works a bit better then a fixed value (8)
r := math.Max(0, math.Ceil(0.31554321636851*math.Pow(float64(c.Precision), 0.654095561044508)))
var p float64
// maxPrec is the largest precision value we can use bit shifts instead of
// math.Pow which is more expensive.
const maxPrec = 3286
if c.Precision <= maxPrec {
p = 1 / float64(uint64(1)<<uint64(r))
} else {
p = math.Pow(2, -r)
}
halved = int(math.Ceil(math.Log(xf/p) / math.Ln2))
// if the value is already less than 1/(2^r) then halfed
// will be negative and we don't need to apply
// the double angle formula because it would hurt performance
// so we'll set halfed to zero
if halved < 0 {
halved = 0
}
sq := getDec(c)
for i := 0; i < halved; i++ {
c.FMA(sq, z, z, one.get())
c.Sqrt(sq, sq)
c.Add(sq, sq, one.get())
c.Quo(z, z, sq)
}
putDec(sq)
var x2 Big
c.Mul(&x2, z, z)
var x2p1 Big
c.Add(&x2p1, &x2, one.get())
return z, &x2, &x2p1, segment, halved
}
func (c Context) getAtanP(x2 *Big) SplitFunc {
var p Big
return func(n uint64) *Big {
// P(n) = 2n for all n > 0
if n == 0 {
return one.get()
}
if n < math.MaxUint64/2 {
p.SetUint64(n * 2)
} else {
c.Mul(&p, p.SetUint64(n), two.get())
}
return c.Mul(&p, &p, x2)
}
}
func (c Context) getAtanQ(x2p1 *Big) SplitFunc {
var q Big
return func(n uint64) *Big {
// B(n) = (2n+1) for all n >= 0
// atanMax is the largest number we can use to compute (2n + 1) without
// overflow.
const atanMax = (math.MaxUint64 - 1) / 2
if n < atanMax {
q.SetUint64((2 * n) + 1)
} else {
c.FMA(&q, q.SetUint64(n), two.get(), one.get())
}
return c.Mul(&q, &q, x2p1)
}
}
// Atan2 calculates arctan of y/x and uses the signs of y and x to determine
// the valid quadrant
//
// Range:
// y input: all real numbers
// x input: all real numbers
// Output: -pi < Atan2(y, x) <= pi
//
// Special cases:
// Atan2(NaN, NaN) = NaN
// Atan2(y, NaN) = NaN
// Atan2(NaN, x) = NaN
// Atan2(±0, x >=0) = ±0
// Atan2(±0, x <= -0) = ±pi
// Atan2(y > 0, 0) = +pi/2
// Atan2(y < 0, 0) = -pi/2
// Atan2(±Inf, +Inf) = ±pi/4
// Atan2(±Inf, -Inf) = ±3pi/4
// Atan2(y, +Inf) = 0
// Atan2(y > 0, -Inf) = +pi
// Atan2(y < 0, -Inf) = -pi
// Atan2(±Inf, x) = ±pi/2
// Atan2(y, x > 0) = Atan(y/x)
// Atan2(y >= 0, x < 0) = Atan(y/x) + pi
// Atan2(y < 0, x < 0) = Atan(y/x) - pi
func (c Context) Atan2(z, y, x *Big) *Big {
if debug {
x.validate()
}
if z.invalidContext(c) {
return z
}
if z.checkNaNs(x, x, atan) {
return z
}
ctx := c.dup()
ctx.Precision += defaultExtraPrecision
switch {
// Special values.
case x.isSpecial(), x.isZero(), y.isSpecial(), y.isZero():
// Save the signbit in case z == y.
sb := y.form & signbit
ctx.atan2Specials(z, x, y)
z.form |= sb
default:
ctx.Atan(z, ctx.Quo(z, y, x))
if x.Sign() < 0 {
pi := ctx.pi(getDec(ctx))
if z.Sign() <= 0 {
ctx.Add(z, z, pi)
} else {
ctx.Sub(z, z, pi)
}
putDec(pi)
}
}
return c.finish(z)
}
// atan2Specials handles atan2 special cases.
//
// Rounding and sign handling are performed by Atan2.
func (c Context) atan2Specials(z, x, y *Big) *Big {
xs := x.Sign()
if y.Sign() == 0 {
if xs >= 0 && !x.Signbit() {
// Atan2(0, x >= +0) = ±0
return z.setZero(0, 0)
}
// Atan2(0, x <= -0) = ±pi
return c.pi(z)
}
if xs == 0 {
// Atan2(y, 0) = ±pi/2
return c.pi2(z)
}
if x.IsInf(0) {
if x.IsInf(+1) {
if y.IsInf(0) {
// Atan2(±Inf, +Inf) = ±pi/4
return c.Quo(z, c.pi(z), four.get())
}
// Atan2(y, +Inf) = ±0
return z.SetUint64(0)
}
if y.IsInf(0) {
// Atan2(±Inf, -Inf) = ±3 * pi/4
c.Quo(z, c.pi(z), four.get())
return c.Mul(z, z, three.get())
}
// Atan2(y, -Inf) = ±pi
return c.pi(z)
}
if y.IsInf(0) {
// Atan2(±Inf, x) = ±pi/2
return c.pi2(z)
}
panic("unreachable")
}
// Cos returns the cosine, in radians, of x.
//
// Range:
// Input: all real numbers
// Output: -1 <= Cos(x) <= 1
//
// Special cases:
// Cos(NaN) = NaN
// Cos(±Inf) = NaN
func (c Context) Cos(z, x *Big) *Big {
if debug {
x.validate()
}
if z.invalidContext(c) {
return z
}
if z.checkNaNs(x, x, sin) {
return z
}
if x.IsInf(0) {
z.Context.Conditions |= InvalidOperation
return z.SetNaN(false)
}
ctx := c.dup()
ctx.Precision += defaultExtraPrecision
negXSq, halved, ok := ctx.prepCosine(z, x)
if !ok {
z.Context.Conditions |= InvalidOperation
return z.SetNaN(false)
}
ctx.Precision += halved
z.Copy(BinarySplitDynamic(ctx,
func(_ uint64) *Big { return one.get() },
getCosineP(negXSq),
func(_ uint64) *Big { return one.get() },
ctx.getCosineQ(),
))
// now undo the half angle bit
for i := 0; i < halved; i++ {
ctx.Mul(z, z, z)
ctx.Mul(z, z, two.get())
ctx.Sub(z, z, one.get())
}
return c.finish(z)
}
func (c Context) prepCosine(z, x *Big) (*Big, int, bool) {
if z == x {
x = getDec(c).Copy(x)
defer putDec(x)
}
var tmp Big
var twoPi Big
// For better results, we need to make sure the value we're
// working with a value is closer to zero.
c.Mul(&twoPi, c.pi(&twoPi), two.get()) // 2 * Pi
if x.CmpAbs(&twoPi) >= 0 {
// For cos to work correctly the input must be in (-2Pi,
// 2Pi).
c.Quo(&tmp, x, &twoPi)
v, ok := tmp.Int64()
if !ok {
return nil, 0, false
}
uv := arith.Abs(v)
// Adjust so we have ceil(v/10) + ctx.Precision, but check for overflows.
// 1+((v-1)/10) will be wildly incorrect for v == 0, but x/y = 0 iff
// x = 0 and y != 0. In this case, -2pi <= x >= 2pi, so we're fine.
prec, carry := bits.Add64(1+((uv-1)/10), uint64(c.Precision), 0)
if carry != 0 || prec > arith.MaxInt {
return nil, 0, false
}
pctx := Context{Precision: int(prec)}
if uv <= math.MaxInt64/2 {
tmp.SetMantScale(v, 0)
}
pctx.Mul(&tmp, &twoPi, &tmp)
// so toRemove = 2*Pi*v so x - toRemove < 2*Pi
c.Sub(z, x, &tmp)
} else {
z.Copy(x)
}
// add 1 to the precision for the up eventual squaring.
c.Precision++
// now preform the half angle.
// we'll repeat this up to log(precision)/log(2) and keep track
// since we'll be dividing x we need to give a bit more precision
// we'll be repeated applying the double angle formula
// we could use a higher angle formula but wouldn't buy us anything.
// Each time we half we'll have to increase the values precision by 1
// and since we'll dividing at most 11 time that means at most 11 digits
// but we'll figure out the minimum time we'll apply the double angle
// formula
// we'll we reduce until it's x <= p where p= 1/2^8 (approx 0.0039)
// we figure out the number of time to divide by solving for r
// in x/p = 2^r so r = log(x/p)/log(2)
xf, _ := z.Float64()
// We only need to do the calculation if xf >= 0.0004. Anything below that
// and we're <= 0.
var halved int
if xf = math.Abs(xf); xf >= 0.0004 {
// Originally: ceil(log(xf/0.0048828125) / ln2)
halved = int(math.Ceil(1.4427*math.Log(xf) + 11))
// The general case is halved > 0, since we only get 0 if xf is very
// close to 0.0004.
if halved > 0 {
// Increase the precision based on the number of divides. Overflow is
// unlikely, but possible.
c.Precision += halved
if c.Precision <= halved {
return nil, 0, false
}
// The maximum value for halved will be 14, given
// ceil(1.4427*log(2*pi)+11) = 14
c.Quo(z, z, tmp.SetUint64(1<<uint64(halved)))
}
}
c.Mul(z, z, z)
z.CopyNeg(z)
return z, halved, true
}
func getCosineP(negXSq *Big) func(n uint64) *Big {
return func(n uint64) *Big {
if n == 0 {
return one.get()
}
return negXSq
}
}
func (c Context) getCosineQ() func(n uint64) *Big {
var q, tmp Big
return func(n uint64) *Big {
// (0) = 1, q(n) = 2n(2n-1) for n > 0
if n == 0 {
return one.get()
}
// most of the time n will be a small number so
// use the fastest method to calculate 2n(2n-1)
const cosine4NMaxN = 2147483648
if n < cosine4NMaxN {
// ((n*n) << 2) - (n << 1)
return q.SetUint64((2 * n) * (2*n - 1))
}
q.SetUint64(n)
c.Mul(&tmp, &q, two.get())
c.Mul(&q, &tmp, &tmp)
return c.Sub(&q, &q, &tmp)
}
}
// Ceil sets z to the least integer value greater than or equal
// to x and returns z.
func (c Context) Ceil(z, x *Big) *Big {
// ceil(x) = -floor(-x)
return c.Neg(z, c.Floor(z, z.CopyNeg(x)))
}
// E sets z to the mathematical constant e and returns z.
func (c Context) E(z *Big) *Big {
if c.Precision <= constPrec {
return c.Set(z, _E.get())
}
var (
sum = z.SetUint64(2)
fac = new(Big).SetUint64(1)
term = new(Big)
prev = new(Big)
)
ctx := c
ctx.Precision += 5
for i := uint64(2); sum.Cmp(prev) != 0; i++ {
// Use term as our intermediate storage for our
// factorial. SetUint64 should be marginally faster than
// ctx.Add(incr, incr, one), but either the costly call
// to Quo makes it difficult to notice.
term.SetUint64(i)
ctx.Mul(fac, fac, term)
ctx.Quo(term, one.get(), fac)
prev.Copy(sum)
ctx.Add(sum, sum, term)
}
return ctx.Set(z, sum)
}
// Exp sets z to e**x and returns z.
func (c Context) Exp(z, x *Big) *Big {
if debug {
x.validate()
}
if z.invalidContext(c) {
return z
}
if z.checkNaNs(x, x, exp) {
return z
}
if x.IsInf(0) {
if x.IsInf(+1) {
// e ** +Inf = +Inf
return z.SetInf(false)
}
// e ** -Inf = 0
return z.SetUint64(0)
}
if x.isZero() {
// e ** 0 = 1
return z.SetUint64(1)
}
z = c.exp(z, x)
if z.IsFinite() && z.Sign() != 0 && z.Precision() < c.Precision {
s := c.Precision - z.Precision()
c.shiftl(z, uint64(s))
z.exp -= s
}
return c.finish(z)
}
func (c Context) exp(z, x *Big) *Big {
if getmsd(x, 1) == 0 {
return z.SetMantScale(1, 0)
}
t := x.Precision() + x.exp
if t < 0 {
t = 0
}
const expMax = 19
if t > expMax {
z.Context.Conditions |= Inexact | Rounded
if x.Signbit() {
z.Context.Conditions |= Subnormal | Underflow | Clamped
return z.SetMantScale(0, -c.etiny())
}
z.Context.Conditions |= Overflow
return z.SetInf(false)
}
// |x| <= 9 * 10**-(prec + 1)
lim := z
if lim == x {
lim = getDec(c)
defer putDec(lim)
}
lim.SetMantScale(9, c.Precision+1)
if x.CmpAbs(lim) <= 0 {
z.Context.Conditions |= Rounded | Inexact
return z.SetMantScale(1, 0)
}
if x.IsInt() {
if v, ok := x.Uint64(); ok && v == 1 {
// e ** 1 = e
return c.E(z)
}
}
// Argument reduction:
// exp(x) = e**r ** 10**k where x = r * 10**k
z.Copy(x)
z.exp -= t
// TODO(eric): figure out if it's possible to make Horner's
// method faster than continued fractions for small
// precisions.
if false && c.Precision <= 300 {
c.expSmall(z, t)
} else {
c.expLarge(z, t)
}
return z
}
// expSmall returns exp(z) using Horner's scheme.
//
// The algorithm is taken from "Variable precision exponential
// function." by T. E. Hull and A. Abrham. 1986.
// https://dl.acm.org/doi/10.1145/6497.6498
func (c Context) expSmall(z *Big, t int) *Big {
p := c.Precision + t + 2
if p < 10 {
p = 10
}
c.Precision = p