-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbigfloat.go
More file actions
1403 lines (1150 loc) · 34.7 KB
/
bigfloat.go
File metadata and controls
1403 lines (1150 loc) · 34.7 KB
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 2023 Tihomir Magdic. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
*/
/*
Package bigfloat implements big float number functionalities: adding, substraction, multiplication, division, rounding, truncation, converting to/from string, comparison, automatic precision.
Also, supports repeating decimals with various formatting.
BigFloat variables can be declared as:
n1, err := bigfloat.Set("7.005")
n2 := bigfloat.SetInt(4)
n3 := bigfloat.New() // zero value is 0
Operations are implemented as methods:
n3.Add(n1, n2)
n3.Sub(n1, n2)
n3.Mul(n1, n2)
n3.Div(n1, n2)
Methods of this form typically return the incoming receiver, to enable simple call chaining:
n3.Mul(n1, n2).Sub(n3, n1)
BigFloat implements stringer so it can be simple printed as:
fmt.Printf("%v\n", n3)
Division supports remainders:
n1.Set(23)
n2.Set(-11)
_, remainder, _ := n3.DivMod(n1, n2)
fmt.Printf("%v div %v = %v (remainder: %v)\n", n1, n2, n3, remainder)
// Output: 23 div -11 = -2 (remainder: 1)
The division also supports arbitrary decimals:
n3.Div(n1, n2, bigfloat.WithDivDecimalPlaces(10))
fmt.Printf("%v / %v = %v\n", n1, n2, n3)
// Output: 23 / -11 = -2.0909090909
Repeating decimals:
_, repeatingDecimals, _ := n3.Div(n1, n2)
fmt.Printf("%v / %v = %v\n", n1, n2, n3.StringF(repeatingDecimals))
// Output: 23 / -11 = -2.(09)
Repeating decimals with different formatting:
fmt.Printf("abs = %v\n", n3.Abs().StringF(repeatingDecimals, bigfloat.WithRepeatingOptions("r", ""), bigfloat.ForceSign(true)))
// Output: abs = +2.r09
Rounding:
n3.Set("1.75125")
d := 4
fmt.Printf("%v\n", n3.Round(d))
// Output: 1.7513
Truncate:
fmt.Printf("trunc(%v) = ", n3)
fmt.Printf("%v\n", n3.Trunc())
// Output: trunc(1.75130) = 1.00000
*/
package bigfloat
import (
"bytes"
"fmt"
"math"
"reflect"
"stranalyzer"
"strconv"
"strings"
)
/*
Function type for division operation.
See: Div
*/
type DivOption func(*divOptionsType)
type divOptionsType struct {
decimalPlaces int
maxDecimalPlaces int
}
/*
Function defines precision in division operation.
Recommended to use repeating decimals.
*/
func WithDivDecimalPlaces(decimalPlaces int) DivOption {
return func(ro *divOptionsType) {
ro.decimalPlaces = decimalPlaces
}
}
/*
Function defines maximum decimals in division
Effective with very long decimals
*/
func WithDivMaxDecimalPlaces(maxDecimalPlaces int) DivOption {
return func(ro *divOptionsType) {
ro.maxDecimalPlaces = maxDecimalPlaces
}
}
/*
Function type for rounding option.
*/
type RoundOption func(*roundOptionsType)
type roundOptionsType struct {
decimalPlaces int
}
/*
Function defines number of decimal places in rounding
See: Round
*/
func WithDecimalPlaces(decimalPlaces int) RoundOption {
return func(ro *roundOptionsType) {
ro.decimalPlaces = decimalPlaces
}
}
/*
Function type for repeating options
*/
type RepeatingOptions func(*repeatingOptionsType)
type repeatingOptionsType struct {
indicatorStart string
indicatorEnd string
}
/*
Function for repeating options
-indicatorStart is placed before first repeating decimal - default is '('
-indicatorEnd is placed after last repeating decimal - default is ')'
*/
func WithRepeatingOptions(indicatorStart, indicatorEnd string) RepeatingOptions {
return func(ro *repeatingOptionsType) {
ro.indicatorStart = indicatorStart
ro.indicatorEnd = indicatorEnd
}
}
/*
Basic type for BigFloat number
*/
type BigFloat struct {
analysis stranalyzer.Analysis
}
/*
Creates new BigFloat number with zero value
*/
func New() *BigFloat {
return &BigFloat{
analysis: stranalyzer.Analysis{
Norm: []byte{'0'},
Sign: 1,
Decimals: 0,
Len: 1,
},
}
}
/*
Sets value of BigFloat number based on value and type of input parameter.
For specific type call SetInt64, SetString etc.
*/
func (f *BigFloat) Set(arg interface{}) (*BigFloat, error) {
var err error
switch value := arg.(type) {
case string:
err = f.SetString(value)
return f, err
case int:
f.SetInt64(int64(value))
case int64:
f.SetInt64(value)
case int8:
f.SetInt64(int64(value))
case int16:
f.SetInt64(int64(value))
case int32:
f.SetInt64(int64(value))
case *BigFloat:
f.analysis = value.Copy().analysis
case BigFloat:
f.analysis = (&value).Copy().analysis
default:
panic("unknown argument")
}
return f, err
}
/*
Creates new BigFloat number according input parameter's type
*/
func Set(arg interface{}) (*BigFloat, error) {
return New().Set(arg)
}
/*
Creates array of BigFloat number according variadic parameters
*/
func NewNumbers(args ...interface{}) ([]*BigFloat, []error) {
result := make([]*BigFloat, len(args))
errors := make([]error, len(args))
for i, arg := range args {
result[i], errors[i] = Set(arg)
}
return result, errors
}
type subProduct struct {
offset int
product []int
}
func maxInt(a, b int) int {
if a > b {
return a
}
return b
}
type correction struct {
offset int
reverse int
}
type alignment struct {
MaxIntLen int
MaxDecLen int
Len int
corrections []correction
}
/*
For internal use
Reads digit at pos position (from beginning), from f BigFloat, with c correction and fixing retrived digit by adding byteFix
*/
func read(pos int, f *BigFloat, c *correction, byteFix int) int {
cPos := f.analysis.Len - pos - c.offset - 1 // calculate reading position
if cPos >= 0 && cPos < f.analysis.Len {
return int(f.analysis.Norm[cPos]) + byteFix
}
return 0
}
/*
For internal use
Reads digit at pos position (backwards from end), from f BigFloat, with c correction and fixing retrived digit by adding byteFix
*/
func reverse_read(pos int, f *BigFloat, c *correction, byteFix int) int {
cPos := pos - c.reverse // calculate reading position
if cPos >= 0 && cPos < f.analysis.Len {
return int(f.analysis.Norm[cPos]) + byteFix
}
return 0
}
type readFnType = func(int, *BigFloat, *correction, int) int
/*
Reads one digit at pos position for every BigFloat in n array with a alignment
readFn can be read (from the beginning) or reverse_read (backwards from end)
*/
func multiRead(pos int, n []*BigFloat, a *alignment, byteFix int, readFn readFnType) []int {
result := make([]int, len(n))
for i := 0; i < len(n); i++ {
result[i] = readFn(pos, n[i], &a.corrections[i], byteFix)
}
return result
}
/*
Calculate alignment two BigFloat numbers
*/
func align(args ...*BigFloat) alignment {
var maxIntLen, maxDecLen int
if len(args) > 0 {
maxIntLen = args[0].analysis.Len - args[0].analysis.Decimals
maxDecLen = args[0].analysis.Decimals
}
for i := 1; i < len(args); i++ {
intLen := args[i].analysis.Len - args[i].analysis.Decimals
decLen := args[i].analysis.Decimals
if intLen > maxIntLen {
maxIntLen = intLen
}
if decLen > maxDecLen {
maxDecLen = decLen
}
}
c := make([]correction, len(args))
for i, arg := range args {
c[i] = correction{
offset: arg.analysis.Decimals - maxDecLen,
reverse: maxIntLen - (arg.analysis.Len - arg.analysis.Decimals),
}
}
return alignment{
MaxIntLen: maxIntLen,
MaxDecLen: maxDecLen,
Len: maxIntLen + maxDecLen,
corrections: c,
}
}
/*
Parse string into BigFloat number
If parsing failed returns error
*/
func (f *BigFloat) SetString(s string) error {
analysis, error := stranalyzer.Analyze(s)
if error != nil {
return error
}
f.analysis = analysis
return nil
}
/*
Create new BigFloat number from string
If parsing failed returns error
*/
func SetString(s string) (*BigFloat, error) {
f := &BigFloat{}
err := f.SetString(s)
return f, err
}
/*
Internal multiplication of two ascii bytes
*/
func mul(a, b byte) int {
return int((a - 48) * (b - 48))
}
/*
Calculate integer division and remainder
*/
func divmod10(a int) (int, int) {
d := a / 10
m := a % 10
return d, m
}
/*
Modifies []byte by adding value
*/
func add(a []byte, value int) []byte {
for i := 0; i < len(a); i++ {
a[i] = byte(int(a[i]) + value)
}
return a
}
/*
Creates new []byte vith initial value
*/
func fill(length int, value byte) []byte {
digits := make([]byte, length)
if value != 0 {
for i := 0; i < len(digits); i++ {
digits[i] = value
}
}
return digits
}
/*
Reverses []byte
*/
func reverse(chars []byte) []byte {
for i1, i2 := 0, len(chars)-1; i1 < i2; i1, i2 = i1+1, i2-1 {
chars[i1], chars[i2] = chars[i2], chars[i1]
}
return chars
}
/*
Divides two BigFloat numbers with DivOption:
decimalPlaces - target decimal places (default is -1 for detecting repeating decimals or remainder 0)
maxDecimalPlaces - safety parameter for the result of division with a very large number of decimal places (default is 1e4 - 10000)
*/
func (f *BigFloat) Div(a, b *BigFloat, options ...DivOption) (*BigFloat, int, error) {
r := &BigFloat{}
return f.divmod(a, b, r, false, options...)
}
/*
Integer division of two BigFloat numbers
Returns integer division and modulus
*/
func (f *BigFloat) DivMod(a, b *BigFloat) (*BigFloat, *BigFloat, error) {
r := &BigFloat{}
_, _, err := f.divmod(a, b, r, true, WithDivDecimalPlaces(0))
return f, r, err
}
/*
Internal divmod - used for Div and DIvMod
bTrunc argument determines if result should be truncated
for DivOption see Div method
*/
func (f *BigFloat) divmod(a, b, remainder *BigFloat, bTrunc bool, options ...DivOption) (*BigFloat, int, error) {
ro := divOptionsType{ // default option values
decimalPlaces: -1,
maxDecimalPlaces: int(1e4),
}
for _, option := range options { // process variadic arguments
option(&ro)
}
if a.IsInt64(0) { // if 1st operand is 0 then result is 0
f.SetInt64(0)
if ro.decimalPlaces >= 0 {
f.SetDecimals(ro.decimalPlaces)
}
return f, 0, nil
} else if b.IsInt64(0) { // if 2nd operand is 0 then return error
return nil, 0, fmt.Errorf("ERROR: Division by zero")
}
aCopy := a.Copy().Abs() // prepare copies of both operands with absolute values
bCopy := b.Copy().Abs()
if (a.analysis.Decimals + b.analysis.Decimals) > 0 { // eliminate decimals in both operands
aCopy.Mul10(a.analysis.Decimals + b.analysis.Decimals)
bCopy.Mul10(a.analysis.Decimals + b.analysis.Decimals)
}
if bCopy.IsInt64(1) { // if 2nd operand is 1 then result is 1st operand
f.analysis = aCopy.analysis
f.Sign(a.analysis.Sign * b.analysis.Sign) // sign of result
if ro.decimalPlaces >= 0 {
f.SetDecimals(ro.decimalPlaces)
}
return f, 0, nil
}
remainder.SetInt64(0) // initial remainder (as in/out parameter)
lastRemainder := SetInt64(0) // penultimate division remainder
result := make([]byte, 0, aCopy.analysis.Len+bCopy.analysis.Len) // reserve enough space for result
aBuf := aCopy.analysis.Norm // running buffer
maxLen := 5 // higher is better - used in converting part of string to int
if maxLen > bCopy.analysis.Len {
maxLen = bCopy.analysis.Len
}
cmpStr := bCopy.analysis.Norm[:maxLen]
divPart2Int, _ := strconv.Atoi(string(cmpStr)) // preparing 2nd operand for division
var divInt byte // int division
initLen := bCopy.analysis.Len - 1 // initial length of 1st operand
if initLen > len(aBuf) {
initLen = len(aBuf)
}
divPart := aBuf[:initLen] // initial 1st operand - skip initial 0 integer division
var digit byte // running digit for append to 1st operand
bDecimals := false // idicator for calculation beyond decimal point
remIndxMap := make(map[string]int) // map of modulus for detecting repeating decimals
repDecimalsInd := -1 // index of modulus of repeating deimals
decimals := 0 // number of divisions decimals
decimalsGoal := ro.decimalPlaces // target decimals
if decimalsGoal >= 0 { // increase target decimals for final rounding
decimalsGoal++
}
for i := bCopy.analysis.Len - 1; true; i++ {
if i >= len(aBuf) { // if calculates beyond decimal point
digit = '0'
if !bDecimals {
bDecimals = true
}
} else {
digit = aBuf[i]
}
if (bDecimals && string(divPart) == "0") || (decimalsGoal > 0 && decimals == decimalsGoal) { // exit loop if calculates beyond decimal point and there is no remainder or if target decimals reached
break
}
if bDecimals { // calculates map for remainder and number of repeating decimals
ind, exists := remIndxMap[string(divPart)]
if exists { // exit loop if repeating decimal detected (target decimals calculates after loop exit)
repDecimalsInd = ind
break
} else {
remIndxMap[string(divPart)] = decimals
}
}
if bDecimals {
decimals++
}
*lastRemainder = BigFloat{ // save remainder in case of exit loop
analysis: stranalyzer.Analysis{
Norm: divPart,
Len: len(divPart),
Decimals: 0,
Sign: 1,
},
}
if string(divPart) == "0" { // fixes 0 remainder for large numbers
divPart[0] = digit
} else {
divPart = append(divPart, digit)
}
if len(divPart) < bCopy.analysis.Len { // integer division is 0 for smaller 1st operand
divInt = 0
} else {
divPart1Int, _ := strconv.Atoi(string(divPart[:len(divPart)-(bCopy.analysis.Len-len(cmpStr))])) // convert str into 1st operand
divInt = byte(divPart1Int / divPart2Int) // guess division of two numbers
}
if divInt > 0 { // if division is greater then 0 multiply and substract to calculate remainder
fProduct := bCopy.Copy()
if divInt > 1 { // if division is greater then 1 then multiply
fProduct.MulInt64(int64(divInt))
}
*remainder = BigFloat{ // create BigFloat for substraction
analysis: stranalyzer.Analysis{
Norm: divPart,
Len: len(divPart),
Decimals: 0,
Sign: 1,
},
}
if fProduct.Compare(remainder) == 1 { // fix wrong division
divInt-- // fix integer division
fProduct.Sub(fProduct, bCopy) // fix product for substraction
}
remainder.Sub(remainder, fProduct) // calculate remainder
divPart = remainder.analysis.Norm
}
if divInt > 0 || len(result) > 0 || bDecimals { // skip leading zeroes
if bDecimals && len(result) == 0 { // append 0 before decimal point
result = append(result, 0)
}
result = append(result, divInt) // append devision result digit
if decimals >= ro.maxDecimalPlaces { // safety loop exit in case of very long division and no repeating decimals detecting
break
}
}
}
result = add(result, 48) // add 48 to every digit to get ascii numbers
repeatDecimals := 0
if repDecimalsInd >= 0 {
repeatDecimals = decimals - repDecimalsInd // calculates number of repeating decimals (2nd return value)
}
if decimalsGoal >= 0 && decimalsGoal > decimals { // fix decimals to target decimals
var repeatStr []byte
if repeatDecimals > 0 { // with repeting decimals
repeatStr = result[len(result)-repeatDecimals:]
repeatDecimals = 0
} else {
repeatStr = []byte{'0'} // with zeroes
}
trailStr := bytes.Repeat(repeatStr, (decimalsGoal-decimals)/len(repeatStr)+1)
trailStr = trailStr[:decimalsGoal-decimals]
result = append(result, trailStr...)
decimals = decimalsGoal
}
f.analysis = stranalyzer.Analysis{ // create division result
Norm: result,
Len: len(result),
Decimals: decimals,
Sign: a.analysis.Sign * b.analysis.Sign, // sign of result
}
if ro.decimalPlaces >= 0 && ro.decimalPlaces < f.analysis.Decimals { // need to round result
if bTrunc { // in case of integer division, decimals are truncated
f.Trunc(WithDecimalPlaces(0))
} else { // round penultimate digit
f.Round(ro.decimalPlaces)
f.SetDecimals(ro.decimalPlaces)
}
*remainder = *lastRemainder // prepare out arg as remainder
remainder.Div10(a.analysis.Decimals + b.analysis.Decimals) // fix decimals in remainder
}
return f, repeatDecimals, nil
}
/*
Multiplication of two BigFLoat numbers
*/
func (f *BigFloat) Mul(a, b *BigFloat) *BigFloat {
if a.IsInt64(0) || b.IsInt64(0) { // check for 0
newDecimals := maxInt(a.analysis.Decimals, b.analysis.Decimals)
return f.SetInt64(0).SetDecimals(newDecimals) // result is 0
} else if a.IsInt64(1) { // if 1st operand is 1 then result is 2nd operand
f.analysis = b.analysis
return f
} else if a.IsInt64(-1) { // if 1st operand is -1 then result is negative 2nd operand
f.analysis = b.analysis
return f.Neg()
} else if b.IsInt64(1) { // if 2nd operand is 1 then result is 1st operand
f.analysis = a.analysis
return f
} else if b.IsInt64(-1) { // if 2nd operand is -1 then result is negative 1st operand
f.analysis = a.analysis
return f.Neg()
}
var r, overflow int // running multiplication result
var resultBuf []subProduct // sub products with offsets
aStr := a.analysis.Norm
bStr := b.analysis.Norm
for bd := 0; bd < len(bStr); bd++ { // long division algorithm
if bStr[bd] == '0' {
continue
}
overflow = 0
sp := subProduct{
offset: b.analysis.Len - bd - 1, // sets offest for sub product addition
}
cBuf := make([]int, 0, len(aStr)+1)
for ad := len(aStr) - 1; ad >= 0; ad-- { // multiply every digit
total := mul(bStr[bd], aStr[ad])
total += overflow
overflow, r = divmod10(total) // calculate overflow
cBuf = append(cBuf, r) // append result digit
}
if overflow != 0 { // if exists add overflow after loop
cBuf = append(cBuf, overflow)
}
sp.product = cBuf // prepare sub products
resultBuf = append(resultBuf, sp)
}
var ppos, s int
overflow = 0
lenP := a.analysis.Len + b.analysis.Len
totalBuf := make([]byte, 0, lenP)
for pos := 0; pos < lenP; pos++ { // calculate sum of sub products
s = overflow
for r = 0; r < len(resultBuf); r++ {
ppos = pos - resultBuf[r].offset
if ppos >= 0 && ppos < len(resultBuf[r].product) {
s += resultBuf[r].product[ppos]
}
}
overflow, r = divmod10(s) // calculate overflow
totalBuf = append(totalBuf, byte(r)) // append sum digit
}
totalBuf = append(totalBuf, byte(overflow)) // add overflow after loop
newDecimals := a.analysis.Decimals + b.analysis.Decimals // calculate number of decimals
totalBuf = reverse(totalBuf) // reverse digits for display (low digits to the right)
if len(totalBuf) > newDecimals { // trim leading zeroes
iTrim := 0
for i := 0; i < len(totalBuf)-newDecimals-1; i++ { // except first digit before decimal point
if totalBuf[i] == 0 {
iTrim++
} else {
break
}
}
totalBuf = totalBuf[iTrim:]
}
if newDecimals > 0 { // trim trailing zeroes
iTrim := 0
for i := 0; i < newDecimals; i++ {
if totalBuf[len(totalBuf)-i-1] == 0 {
iTrim++
} else {
break
}
}
totalBuf = totalBuf[:len(totalBuf)-iTrim]
newDecimals -= iTrim
}
totalBuf = add(totalBuf, 48) // add 48 to every digit to get ascii numbers
f.analysis = stranalyzer.Analysis{ // prepare result
Norm: totalBuf,
Len: len(totalBuf),
Decimals: newDecimals,
Sign: a.analysis.Sign * b.analysis.Sign,
}
return f
}
/*
Returns if BigFloat equals number n
*/
func (f *BigFloat) IsInt64(n int64) bool {
nFloat := BigFloat{}
nFloat.SetInt64(n).SetDecimals(f.analysis.Decimals)
return (f.analysis.Sign == nFloat.analysis.Sign) && // checks if number are equals - cannot compare with f.analysis.Sign == nFloat.analysis as in analysis is []byte
(f.analysis.Decimals == nFloat.analysis.Decimals) &&
(f.analysis.Len == nFloat.analysis.Len) &&
(string(f.analysis.Norm) == string(nFloat.analysis.Norm))
}
/*
Truncates integer part of number and returns decimals only
*/
func (f *BigFloat) Frac() *BigFloat {
if (f.analysis.Len - f.analysis.Decimals) > 0 {
f.analysis.Norm = append([]byte{'0'}, f.analysis.Norm[f.analysis.Len-f.analysis.Decimals:]...)
f.analysis.Len = len(f.analysis.Norm)
for i := 0; i < f.analysis.Len; i++ {
if f.analysis.Norm[i] != '0' {
return f
}
}
f.analysis.Sign = 1
}
return f
}
/*
Multiply BigFloat with int64
*/
func (f *BigFloat) MulInt64(n int64) *BigFloat {
if n == 0 { // result is 0 with a predefined number of decimals
f.analysis.Sign = 1
f.analysis.Norm = fill(f.analysis.Decimals+1, '0')
f.analysis.Len = f.analysis.Decimals + 1
return f
} else if n == 1 { // same BigFloat as result
return f
} else if n == -1 { // for -1 result is opposite sign except for 0
if !f.IsInt64(0) {
f.analysis.Sign *= -1
}
return f
}
nStr := strconv.FormatInt(n, 10) // check if n is a multiple of 10
trimmedString := strings.TrimRight(nStr, "0")
numZeroes := len(nStr) - len(trimmedString)
if (numZeroes > 0) && ((trimmedString == "1") || (trimmedString == "-1")) { // if n is a multiple of 10
if trimmedString == "-1" { // calculate sign
f.analysis.Sign *= -1
}
return f.Mul10(numZeroes) // simple move decimals
}
nFloat := BigFloat{} // in every other case multiply two BigFloat numbers
nFloat.SetInt64(n)
return f.Mul(f, &nFloat)
}
/*
Truncate decimals in BigFloat number
RoundOption defines number of decimals in result
*/
func (f *BigFloat) Trunc(options ...RoundOption) *BigFloat {
ro := roundOptionsType{
decimalPlaces: f.analysis.Decimals,
}
for _, option := range options {
option(&ro)
}
if ro.decimalPlaces < 0 {
panic("ERROR: Negative decimal places. Decimal places should be 0 or positive")
}
for i := f.analysis.Len - f.analysis.Decimals; i < f.analysis.Len; i++ { // set '0' as decimals digits
f.analysis.Norm[i] = '0'
}
f.SetDecimals(ro.decimalPlaces)
return f
}
/*
Set target decimals
*/
func (f *BigFloat) SetDecimals(n int) *BigFloat {
if n == f.analysis.Decimals { // no need to change
f.Sign(f.analysis.Sign) // checks negative sign for 0 e.g. (-0.1).SetDecimals(0) => 0
return f
} else if n > f.analysis.Decimals { // need to add zeroes
zeroes := fill(n-f.analysis.Decimals, '0')
f.analysis.Norm = append(f.analysis.Norm, zeroes...)
} else { // need to trim trailing decimals
f.analysis.Norm = f.analysis.Norm[:f.analysis.Len-f.analysis.Decimals+n]
}
f.analysis.Decimals = n
f.analysis.Len = len(f.analysis.Norm)
f.Sign(f.analysis.Sign) // checks negative sign for 0 e.g. (-0.1).SetDecimals(0) => 0
return f
}
/*
Adds two BigFloat numbers
Warning: Only for numbers with the same sign
*/
func (f *BigFloat) add(a, b *BigFloat) *BigFloat {
n := []*BigFloat{a, b} // array of operands
alignment := align(n...) // calculate alignemnt with decimals
var r int
overflow := 0
sum := 0
totalBuf := make([]byte, 0, alignment.Len+1) // result of addition
for p := 0; p < alignment.Len; p++ {
sum = overflow
v := multiRead(p, n, &alignment, -48, read) // read operands digits
sum += v[0] + v[1] // calculate sum
overflow, r = divmod10(sum) // calculate result digit and overflow
totalBuf = append(totalBuf, byte(r)) // append result digit
}
totalBuf = append(totalBuf, byte(overflow)) // add overflow after loop
totalBuf = reverse(totalBuf)
if len(totalBuf) > alignment.MaxDecLen { // trim leading zeroes
iTrim := 0
for i := 0; i < len(totalBuf)-alignment.MaxDecLen-1; i++ { // except first digit before decimal point
if totalBuf[i] == 0 {
iTrim++
} else {
break
}
}
totalBuf = totalBuf[iTrim:]
}
totalBuf = add(totalBuf, 48) // add 48 to every digit to get ascii numbers
f.analysis = stranalyzer.Analysis{ // prepare result
Norm: totalBuf,
Len: len(totalBuf),
Decimals: alignment.MaxDecLen,
Sign: a.analysis.Sign, // same signe of both operands
}
return f
}
/*
Adds two BigFloat numbers
See following table for cases when operands are swapped and how result sign is set
Addition:
| a | b | a + b | swap | sign of result | abs(a) +- abs(b) |
|---:|----:|:------:|:----:|:----------------:|:----------------:|
| -5 | -8 | -(5+8) | no | abs bigger | 5+8 |
| -8 | -5 | -(8+5) | no | abs bigger | 8+5 |
| 5 | -8 | -(8-5) | yes | abs bigger | 8-5 |
| -8 | 5 | -(8-5) | no | abs bigger | 8-5 |
| -5 | 8 | 8-5 | yes | abs bigger | 8-5 |
| 8 | -5 | 8-5 | no | abs bigger | 8-5 |
| 5 | 8 | 5+8 | no | abs bigger | 5+8 |
| 8 | 5 | 8+5 | no | abs bigger | 8+5 |
*/
func (f *BigFloat) Add(a, b *BigFloat) *BigFloat {
if a.IsInt64(0) { // if 1st operand is 0 then result is 2nd operand (0 + B = B)
f.analysis = b.analysis
return f
} else if b.IsInt64(0) { // if 2nd operand is 0 then result is 1st operand (A + 0 = A)
f.analysis = a.analysis
return f
}
if a.analysis.Sign == b.analysis.Sign { // if both operands have same signs call internal add
return f.add(a, b)
} else { // opposite signs
f1, f2 := a.Copy(), b.Copy()
sign := a.analysis.Sign
cmp := a.CompareAbs(b)
if cmp == 0 { // if numbers are opposite then result is 0 (A + -A = 0)
newDecimals := int(math.Max(float64(a.analysis.Decimals), float64(b.analysis.Decimals)))
return f.SetInt64(0).SetDecimals(newDecimals)
} else if cmp < 0 { // if 1st operand is smaller then 2nd then swap operands
f1, f2 = f2, f1
sign = b.analysis.Sign
}
f1.Abs() // ignore signs
f2.Abs()
f.sub(f1, f2) // substract smaller operand from bigger operand
f.Sign(sign) // set result sign
return f
}
}
/*
Internal method for substraction
*/
func (f *BigFloat) sub(a, b *BigFloat) (*BigFloat, error) {
n := []*BigFloat{a, b} // array of operands
alignment := align(n...) // calculate alignemnt with decimals
var diff, overflow int // running difference as result and overflow
totalBuf := make([]byte, 0, alignment.MaxIntLen+1) // buffer for result digits
for i := 0; i < alignment.Len; i++ { // for all digits
v := multiRead(i, n, &alignment, -48, read) // read aligned digits as i position
v[0] = v[0] - overflow // substract overflow from previous substraction
if v[0] < v[1] { // negative difference so calculate for overflow
overflow = 1
v[0] += 10