-
Notifications
You must be signed in to change notification settings - Fork 1
/
fnmathtrig.go
1628 lines (1499 loc) · 42.2 KB
/
fnmathtrig.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 2017 Baliance. All rights reserved.
//
// Use of this source code is governed by the terms of the Affero GNU General
// Public License version 3.0 as published by the Free Software Foundation and
// appearing in the file LICENSE included in the packaging of this file. A
// commercial license can be purchased by contacting sales@baliance.com.
package formula
import (
"bytes"
"fmt"
"math"
"math/rand"
"strconv"
"strings"
"time"
)
var rnd *rand.Rand
func init() {
rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
RegisterFunction("ABS", makeMathWrapper("ASIN", math.Abs))
RegisterFunction("ACOS", makeMathWrapper("ASIN", math.Acos))
RegisterFunction("ACOSH", makeMathWrapper("ASIN", math.Acosh))
RegisterFunction("_xlfn.ACOT", makeMathWrapper("ACOT", func(v float64) float64 { return math.Pi/2 - math.Atan(v) }))
RegisterFunction("_xlfn.ACOTH", makeMathWrapper("ACOTH", func(v float64) float64 { return math.Atanh(1 / v) }))
// TODO: RegisterFunction("_xlfn.AGGREGATE", Aggregate) // lots of dependencies
RegisterFunction("_xlfn.ARABIC", Arabic)
RegisterFunction("ASIN", makeMathWrapper("ASIN", math.Asin))
RegisterFunction("ASINH", makeMathWrapper("ASINH", math.Asinh))
RegisterFunction("ATAN", makeMathWrapper("ATAN", math.Atan))
RegisterFunction("ATANH", makeMathWrapper("ATANH", math.Atanh))
RegisterFunction("ATAN2", Atan2)
RegisterFunction("_xlfn.BASE", Base)
RegisterFunction("CEILING", Ceiling)
RegisterFunction("_xlfn.CEILING.MATH", CeilingMath)
RegisterFunction("_xlfn.CEILING.PRECISE", CeilingPrecise)
RegisterFunction("COMBIN", Combin)
RegisterFunction("_xlfn.COMBINA", Combina)
RegisterFunction("COS", makeMathWrapper("COS", math.Cos))
RegisterFunction("COSH", makeMathWrapper("COSH", math.Cosh))
RegisterFunction("_xlfn.COT", makeMathWrapperInv("COT", math.Tan))
RegisterFunction("_xlfn.COTH", makeMathWrapperInv("COTH", math.Tanh))
RegisterFunction("_xlfn.CSC", makeMathWrapperInv("CSC", math.Sin))
RegisterFunction("_xlfn.CSCH", makeMathWrapperInv("CSC", math.Sinh))
RegisterFunction("_xlfn.DECIMAL", Decimal)
RegisterFunction("DEGREES", Degrees)
RegisterFunction("EVEN", Even)
RegisterFunction("EXP", makeMathWrapper("EXP", math.Exp))
RegisterFunction("FACT", Fact)
RegisterFunction("FACTDOUBLE", FactDouble)
RegisterFunction("FLOOR", Floor)
RegisterFunction("_xlfn.FLOOR.MATH", FloorMath)
RegisterFunction("_xlfn.FLOOR.PRECISE", FloorPrecise)
RegisterFunction("GCD", GCD)
RegisterFunction("INT", Int)
RegisterFunction("ISO.CEILING", CeilingPrecise) // appears to be the same from what I can tell
RegisterFunction("LCM", LCM)
RegisterFunction("LN", makeMathWrapper("LN", math.Log))
RegisterFunction("LOG", Log)
RegisterFunction("LOG10", makeMathWrapper("LOG10", math.Log10))
RegisterFunction("MDETERM", MDeterm)
// RegisterFunction("MINVERSE", MInverse) // TODO: skipping the other matrix functinos, not sure how common they are
// RegisterFunction("MMULT"
RegisterFunction("MOD", Mod)
RegisterFunction("MROUND", Mround)
RegisterFunction("MULTINOMIAL", Multinomial)
RegisterFunction("_xlfn.MUNIT", Munit)
RegisterFunction("ODD", Odd)
RegisterFunction("PI", Pi)
RegisterFunction("POWER", Power)
RegisterFunction("PRODUCT", Product)
RegisterFunction("QUOTIENT", Quotient)
RegisterFunction("RADIANS", Radians)
RegisterFunction("RAND", Rand)
RegisterFunction("RANDBETWEEN", RandBetween)
RegisterFunction("ROMAN", Roman)
RegisterFunction("ROUND", Round)
RegisterFunction("ROUNDDOWN", RoundDown)
RegisterFunction("ROUNDUP", RoundUp)
RegisterFunction("_xlfn.SEC", makeMathWrapperInv("SEC", math.Cos))
RegisterFunction("_xlfn.SECH", makeMathWrapperInv("SECH", math.Cosh))
RegisterFunction("SERIESSUM", SeriesSum)
RegisterFunction("SIGN", Sign)
RegisterFunction("SIN", makeMathWrapper("SIN", math.Sin))
RegisterFunction("SINH", makeMathWrapper("SINH", math.Sinh))
RegisterFunction("SQRT", makeMathWrapper("SQRT", math.Sqrt))
RegisterFunction("SQRTPI", makeMathWrapper("SQRTPI", func(v float64) float64 { return math.Sqrt(v * math.Pi) }))
// RegisterFunction("SUBTOTAL"
RegisterFunction("SUM", Sum)
// RegisterFunction("SUMIF",
// RegisterFunction("SUMIFS",
// RegisterFunction("SUMIFS",
RegisterFunction("SUMPRODUCT", SumProduct)
RegisterFunction("SUMSQ", SumSquares)
//RegisterFunction("SUMX2MY2"
//RegisterFunction("SUMX2PY2"
//RegisterFunction("SUMXMY2"
RegisterFunction("TAN", makeMathWrapper("TAN", math.Tan))
RegisterFunction("TANH", makeMathWrapper("TANH", math.Tanh))
RegisterFunction("TRUNC", Trunc)
}
// makeMathWrapper is used to wrap single argument math functions from the Go
// standard library and present them as a spreadsheet function.
func makeMathWrapper(name string, fn func(x float64) float64) Function {
return func(args []Result) Result {
if len(args) != 1 {
return MakeErrorResult(name + " requires one argument")
}
arg := args[0].AsNumber()
switch arg.Type {
case ResultTypeNumber:
v := fn(arg.ValueNumber)
if math.IsNaN(v) {
return MakeErrorResult(name + " returned NaN")
}
if math.IsInf(v, 0) {
return MakeErrorResult(name + " returned infinity")
}
return MakeNumberResult(v)
case ResultTypeList, ResultTypeString:
return MakeErrorResult(name + " requires a numeric argument")
case ResultTypeError:
return arg
default:
return MakeErrorResult(fmt.Sprintf("unhandled %s() argument type %s", name, arg.Type))
}
}
}
func makeMathWrapperInv(name string, fn func(x float64) float64) Function {
return func(args []Result) Result {
if len(args) != 1 {
return MakeErrorResult(name + " requires one argument")
}
arg := args[0].AsNumber()
switch arg.Type {
case ResultTypeNumber:
v := fn(arg.ValueNumber)
if math.IsNaN(v) {
return MakeErrorResult(name + " returned NaN")
}
if math.IsInf(v, 0) {
return MakeErrorResult(name + " returned infinity")
}
if v == 0 {
return MakeErrorResultType(ErrorTypeDivideByZero, name+" divide by zero")
}
return MakeNumberResult(1 / v)
case ResultTypeList, ResultTypeString:
return MakeErrorResult(name + " requires a numeric argument")
case ResultTypeError:
return arg
default:
return MakeErrorResult(fmt.Sprintf("unhandled %s() argument type %s", name, arg.Type))
}
}
}
// Atan2 implements the Excel ATAN2 function. It accepts two numeric arguments,
// and the arguments are (x,y), reversed from normal to match Excel's behaviour.
func Atan2(args []Result) Result {
if len(args) != 2 {
return MakeErrorResult("ATAN2 requires two arguments")
}
arg1 := args[0].AsNumber()
arg2 := args[1].AsNumber()
if arg1.Type == ResultTypeNumber && arg2.Type == ResultTypeNumber {
// args are swapped here
v := math.Atan2(arg2.ValueNumber, arg1.ValueNumber)
if v != v {
return MakeErrorResult("ATAN2 returned NaN")
}
return MakeNumberResult(v)
}
for _, t := range []ResultType{arg1.Type, arg2.Type} {
switch t {
case ResultTypeList, ResultTypeString:
return MakeErrorResult("ATAN2 requires a numeric argument")
case ResultTypeError:
return arg1
default:
return MakeErrorResult(fmt.Sprintf("unhandled ATAN2() argument type %s", t))
}
}
return MakeErrorResult("unhandled error for ATAN2()")
}
// Arabic implements the Excel ARABIC function which parses roman numerals. It
// accepts one numeric argument.
func Arabic(args []Result) Result {
if len(args) != 1 {
return MakeErrorResult("ARABIC requires one argument")
}
arg := args[0]
switch arg.Type {
case ResultTypeNumber, ResultTypeList, ResultTypeEmpty:
return MakeErrorResult("ARABIC requires a string argument argument")
case ResultTypeString:
res := 0.0
last := 0.0
for _, c := range arg.ValueString {
digit := 0.0
switch c {
case 'I':
digit = 1
case 'V':
digit = 5
case 'X':
digit = 10
case 'L':
digit = 50
case 'C':
digit = 100
case 'D':
digit = 500
case 'M':
digit = 1000
}
res += digit
switch {
// repeated digits
case last == digit &&
(last == 5 || last == 50 || last == 500):
return MakeErrorResult("invalid ARABIC format")
// simpler form
case 2*last == digit:
return MakeErrorResult("invalid ARABIC format")
}
if last < digit {
res -= 2 * last
}
last = digit
}
return MakeNumberResult(res)
case ResultTypeError:
return arg
default:
return MakeErrorResult(fmt.Sprintf("unhandled ACOSH() argument type %s", arg.Type))
}
}
// CeilingMath implements _xlfn.CEILING.MATH which rounds numbers to the nearest
// multiple of the second argument, toward or away from zero as specified by the
// third argument.
func CeilingMath(args []Result) Result {
if len(args) == 0 {
return MakeErrorResult("CEILING.MATH() requires at least one argument")
}
if len(args) > 3 {
return MakeErrorResult("CEILING.MATH() allows at most three arguments")
}
// number to round
number := args[0].AsNumber()
if number.Type != ResultTypeNumber {
return MakeErrorResult("first argument to CEILING.MATH() must be a number")
}
// significance
significance := float64(1)
if number.ValueNumber < 0 {
significance = -1
}
if len(args) > 1 {
sigArg := args[1].AsNumber()
if sigArg.Type != ResultTypeNumber {
return MakeErrorResult("second argument to CEILING.MATH() must be a number")
}
significance = sigArg.ValueNumber
}
// round direction
direction := float64(1)
if len(args) > 2 {
dirArg := args[2].AsNumber()
if dirArg.Type != ResultTypeNumber {
return MakeErrorResult("third argument to CEILING.MATH() must be a number")
}
direction = dirArg.ValueNumber
}
if len(args) == 1 {
return MakeNumberResult(math.Ceil(number.ValueNumber))
}
v := number.ValueNumber
v, res := math.Modf(v / significance)
if res != 0 {
if number.ValueNumber > 0 {
v++
} else if direction < 0 {
v--
}
}
return MakeNumberResult(v * significance)
}
// Ceiling is an implementation of the CEILING function which
// returns the ceiling of a number.
func Ceiling(args []Result) Result {
if len(args) == 0 {
return MakeErrorResult("CEILING() requires at least one argument")
}
if len(args) > 2 {
return MakeErrorResult("CEILING() allows at most two arguments")
}
// number to round
number := args[0].AsNumber()
if number.Type != ResultTypeNumber {
return MakeErrorResult("first argument to CEILING() must be a number")
}
// significance
significance := float64(1)
if number.ValueNumber < 0 {
significance = -1
}
if len(args) > 1 {
sigArg := args[1].AsNumber()
if sigArg.Type != ResultTypeNumber {
return MakeErrorResult("second argument to CEILING() must be a number")
}
significance = sigArg.ValueNumber
}
if significance < 0 && number.ValueNumber > 0 {
return MakeErrorResultType(ErrorTypeNum, "negative sig to CEILING() invalid")
}
if len(args) == 1 {
return MakeNumberResult(math.Ceil(number.ValueNumber))
}
v := number.ValueNumber
v, res := math.Modf(v / significance)
if res > 0 {
v++
}
return MakeNumberResult(v * significance)
}
// CeilingPrecise is an implementation of the CEILING.PRECISE function which
// returns the ceiling of a number.
func CeilingPrecise(args []Result) Result {
if len(args) == 0 {
return MakeErrorResult("CEILING.PRECISE() requires at least one argument")
}
if len(args) > 2 {
return MakeErrorResult("CEILING.PRECISE() allows at most two arguments")
}
// number to round
number := args[0].AsNumber()
if number.Type != ResultTypeNumber {
return MakeErrorResult("first argument to CEILING.PRECISE() must be a number")
}
// significance
significance := float64(1)
if number.ValueNumber < 0 {
significance = -1
}
if len(args) > 1 {
sigArg := args[1].AsNumber()
if sigArg.Type != ResultTypeNumber {
return MakeErrorResult("second argument to CEILING.PRECISE() must be a number")
}
// don't care about sign of significance
significance = math.Abs(sigArg.ValueNumber)
}
if len(args) == 1 {
return MakeNumberResult(math.Ceil(number.ValueNumber))
}
v := number.ValueNumber
v, res := math.Modf(v / significance)
if res != 0 {
if number.ValueNumber > 0 {
v++
}
}
return MakeNumberResult(v * significance)
}
// Base is an implementation of the Excel BASE function that returns a string
// form of an integer in a specified base and of a minimum length with padded
// zeros.
func Base(args []Result) Result {
if len(args) < 2 {
return MakeErrorResult("BASE() requires at least two arguments")
}
if len(args) > 3 {
return MakeErrorResult("BASE() allows at most three arguments")
}
// number to convert
number := args[0].AsNumber()
if number.Type != ResultTypeNumber {
return MakeErrorResult("first argument to BASE() must be a number")
}
radixArg := args[1].AsNumber()
if radixArg.Type != ResultTypeNumber {
return MakeErrorResult("second argument to BASE() must be a number")
}
radix := int(radixArg.ValueNumber)
if radix < 0 || radix > 36 {
return MakeErrorResult("radix must be in the range [0,36]")
}
// min length of result
minLength := 0
if len(args) > 2 {
lenArg := args[2].AsNumber()
if lenArg.Type != ResultTypeNumber {
return MakeErrorResult("third argument to BASE() must be a number")
}
minLength = int(lenArg.ValueNumber)
}
s := strconv.FormatInt(int64(number.ValueNumber), radix)
if len(s) < minLength {
s = strings.Repeat("0", minLength-len(s)) + s
}
return MakeStringResult(s)
}
// Combin is an implementation of the Excel COMBINA function whic returns the
// number of combinations.
func Combin(args []Result) Result {
if len(args) != 2 {
return MakeErrorResult("COMBIN() requires two argument")
}
nArg := args[0].AsNumber()
kArg := args[1].AsNumber()
if nArg.Type != ResultTypeNumber || kArg.Type != ResultTypeNumber {
return MakeErrorResult("COMBIN() requires numeric arguments")
}
n := math.Trunc(nArg.ValueNumber)
k := math.Trunc(kArg.ValueNumber)
if k > n {
return MakeErrorResult("COMBIN() requires k <= n")
}
if k == n || k == 0 {
return MakeNumberResult(1)
}
res := float64(1)
for i := float64(1); i <= k; i++ {
res *= (n + 1 - i) / i
}
return MakeNumberResult(res)
}
// Combina is an implementation of the Excel COMBINA function whic returns the
// number of combinations with repetitions.
func Combina(args []Result) Result {
if len(args) != 2 {
return MakeErrorResult("COMBINA() requires two argument")
}
nArg := args[0].AsNumber()
kArg := args[1].AsNumber()
if nArg.Type != ResultTypeNumber || kArg.Type != ResultTypeNumber {
return MakeErrorResult("COMBINA() requires numeric arguments")
}
n := math.Trunc(nArg.ValueNumber)
k := math.Trunc(kArg.ValueNumber)
if n < k {
return MakeErrorResult("COMBINA() requires n > k")
}
if n == 0 {
return MakeNumberResult(0)
}
args[0] = MakeNumberResult(n + k - 1)
args[1] = MakeNumberResult(n - 1)
return Combin(args)
}
// Decimal is an implementation of the Excel function DECIMAL() that parses a string
// in a given base and returns the numeric result.
func Decimal(args []Result) Result {
if len(args) != 2 {
return MakeErrorResult("DECIMAL() requires two arguments")
}
sArg := args[0].AsString()
if sArg.Type != ResultTypeString {
return MakeErrorResult("DECIMAL() requires string first argument")
}
baseArg := args[1].AsNumber()
if baseArg.Type != ResultTypeNumber {
return MakeErrorResult("DECIMAL() requires number second argument")
}
sv := sArg.ValueString
if len(sv) > 2 && (strings.HasPrefix(sv, "0x") || strings.HasPrefix(sv, "0X")) {
sv = sv[2:]
}
i, err := strconv.ParseInt(sv, int(baseArg.ValueNumber), 64)
if err != nil {
return MakeErrorResult("DECIMAL() error in conversion")
}
return MakeNumberResult(float64(i))
}
// Degrees is an implementation of the Excel function DEGREES() that converts
// radians to degrees.
func Degrees(args []Result) Result {
if len(args) != 1 {
return MakeErrorResult("DEGREES() requires one argument")
}
vArg := args[0].AsNumber()
if vArg.Type != ResultTypeNumber {
return MakeErrorResult("DEGREES() requires number argument")
}
return MakeNumberResult(180.0 / math.Pi * vArg.ValueNumber)
}
// Even is an implementation of the Excel EVEN() that rounds a number to the
// nearest even integer.
func Even(args []Result) Result {
if len(args) != 1 {
return MakeErrorResult("EVEN() requires one argument")
}
vArg := args[0].AsNumber()
if vArg.Type != ResultTypeNumber {
return MakeErrorResult("EVEN() requires number argument")
}
sign := math.Signbit(vArg.ValueNumber)
m, r := math.Modf(vArg.ValueNumber / 2)
v := m * 2
if r != 0 {
if !sign {
v += 2
} else {
v -= 2
}
}
return MakeNumberResult(v)
}
func fact(f float64) float64 {
res := float64(1)
for i := float64(2); i <= f; i++ {
res *= i
}
return res
}
// Fact is an implementation of the excel FACT function which returns the
// factorial of a positive numeric input.
func Fact(args []Result) Result {
if len(args) != 1 {
return MakeErrorResult("FACT() accepts a single numeric argument")
}
vArg := args[0].AsNumber()
if vArg.Type != ResultTypeNumber {
return MakeErrorResult("FACT() accepts a single numeric argument")
}
if vArg.ValueNumber < 0 {
return MakeErrorResult("FACT() accepts only positive arguments")
}
return MakeNumberResult(fact(vArg.ValueNumber))
}
// FactDouble is an implementation of the excel FACTDOUBLE function which
// returns the double factorial of a positive numeric input.
func FactDouble(args []Result) Result {
if len(args) != 1 {
return MakeErrorResult("FACTDOUBLE() accepts a single numeric argument")
}
vArg := args[0].AsNumber()
if vArg.Type != ResultTypeNumber {
return MakeErrorResult("FACTDOUBLE() accepts a single numeric argument")
}
if vArg.ValueNumber < 0 {
return MakeErrorResult("FACTDOUBLE() accepts only positive arguments")
}
res := float64(1)
v := math.Trunc(vArg.ValueNumber)
for i := v; i > 1; i -= 2 {
res *= i
}
return MakeNumberResult(res)
}
// FloorMath implements _xlfn.FLOOR.MATH which rounds numbers down to the
// nearest multiple of the second argument, toward or away from zero as
// specified by the third argument.
func FloorMath(args []Result) Result {
if len(args) == 0 {
return MakeErrorResult("FLOOR.MATH() requires at least one argument")
}
if len(args) > 3 {
return MakeErrorResult("FLOOR.MATH() allows at most three arguments")
}
// number to round
number := args[0].AsNumber()
if number.Type != ResultTypeNumber {
return MakeErrorResult("first argument to FLOOR.MATH() must be a number")
}
// significance
significance := float64(1)
if number.ValueNumber < 0 {
significance = -1
}
if len(args) > 1 {
sigArg := args[1].AsNumber()
if sigArg.Type != ResultTypeNumber {
return MakeErrorResult("second argument to FLOOR.MATH() must be a number")
}
significance = sigArg.ValueNumber
}
// round direction
direction := float64(1)
if len(args) > 2 {
dirArg := args[2].AsNumber()
if dirArg.Type != ResultTypeNumber {
return MakeErrorResult("third argument to FLOOR.MATH() must be a number")
}
direction = dirArg.ValueNumber
}
if len(args) == 1 {
return MakeNumberResult(math.Floor(number.ValueNumber))
}
v := number.ValueNumber
v, res := math.Modf(v / significance)
if res != 0 && number.ValueNumber < 0 && direction > 0 {
v++
}
return MakeNumberResult(v * significance)
}
// Floor is an implementation of the FlOOR function.
func Floor(args []Result) Result {
if len(args) != 2 {
return MakeErrorResult("FLOOR() requires two arguments")
}
// number to round
number := args[0].AsNumber()
if number.Type != ResultTypeNumber {
return MakeErrorResult("first argument to FLOOR() must be a number")
}
// significance
var significance float64
sigArg := args[1].AsNumber()
if sigArg.Type != ResultTypeNumber {
return MakeErrorResult("second argument to FLOOR() must be a number")
}
significance = sigArg.ValueNumber
if significance < 0 && number.ValueNumber >= 0 {
return MakeErrorResultType(ErrorTypeNum, "invalid arguments to FLOOR")
}
v := number.ValueNumber
v, res := math.Modf(v / significance)
if res != 0 {
if number.ValueNumber < 0 && res < 0 {
v--
}
}
return MakeNumberResult(v * significance)
}
// FloorPrecise is an implementation of the FlOOR.PRECISE function.
func FloorPrecise(args []Result) Result {
if len(args) == 0 {
return MakeErrorResult("FLOOR.PRECISE() requires at least one argument")
}
if len(args) > 2 {
return MakeErrorResult("FLOOR.PRECISE() allows at most two arguments")
}
// number to round
number := args[0].AsNumber()
if number.Type != ResultTypeNumber {
return MakeErrorResult("first argument to FLOOR.PRECISE() must be a number")
}
// significance
significance := float64(1)
if number.ValueNumber < 0 {
significance = -1
}
if len(args) > 1 {
sigArg := args[1].AsNumber()
if sigArg.Type != ResultTypeNumber {
return MakeErrorResult("second argument to FLOOR.PRECISE() must be a number")
}
// don't care about sign of significance
significance = math.Abs(sigArg.ValueNumber)
}
if len(args) == 1 {
return MakeNumberResult(math.Floor(number.ValueNumber))
}
v := number.ValueNumber
v, res := math.Modf(v / significance)
if res != 0 {
if number.ValueNumber < 0 {
v--
}
}
return MakeNumberResult(v * significance)
}
func gcd(a, b float64) float64 {
a = math.Trunc(a)
b = math.Trunc(b)
if a == 0 {
return b
}
if b == 0 {
return a
}
for a != b {
if a > b {
a = a - b
} else {
b = b - a
}
}
return a
}
// GCD implements the Excel GCD() function which returns the greatest common
// divisor of a range of numbers.
func GCD(args []Result) Result {
if len(args) == 0 {
return MakeErrorResult("GCD() requires at least one argument")
}
numbers := []float64{}
for _, arg := range args {
switch arg.Type {
case ResultTypeString:
na := arg.AsNumber()
if na.Type != ResultTypeNumber {
return MakeErrorResult("GCD() only accepts numeric arguments")
}
numbers = append(numbers, na.ValueNumber)
case ResultTypeList, ResultTypeArray:
res := GCD(arg.ListValues())
if res.Type != ResultTypeNumber {
return res
}
numbers = append(numbers, res.ValueNumber)
case ResultTypeNumber:
numbers = append(numbers, arg.ValueNumber)
case ResultTypeError:
return arg
default:
return MakeErrorResult(fmt.Sprintf("GCD() unsupported argument type %s", arg.Type))
}
}
if numbers[0] < 0 {
return MakeErrorResult("GCD() only accepts positive arguments")
}
if len(numbers) == 1 {
return MakeNumberResult(numbers[0])
}
res := numbers[0]
for i := 1; i < len(numbers); i++ {
if numbers[i] < 0 {
return MakeErrorResult("GCD() only accepts positive arguments")
}
res = gcd(res, numbers[i])
}
return MakeNumberResult(res)
}
func lcm(a, b float64) float64 {
a = math.Trunc(a)
b = math.Trunc(b)
if a == 0 && b == 0 {
return 0
}
return a * b / gcd(a, b)
}
// LCM implements the Excel LCM() function which returns the least common
// multiple of a range of numbers.
func LCM(args []Result) Result {
if len(args) == 0 {
return MakeErrorResult("LCM() requires at least one argument")
}
numbers := []float64{}
for _, arg := range args {
switch arg.Type {
case ResultTypeString:
na := arg.AsNumber()
if na.Type != ResultTypeNumber {
return MakeErrorResult("LCM() only accepts numeric arguments")
}
numbers = append(numbers, na.ValueNumber)
case ResultTypeList:
res := LCM(arg.ValueList)
if res.Type != ResultTypeNumber {
return res
}
numbers = append(numbers, res.ValueNumber)
case ResultTypeNumber:
numbers = append(numbers, arg.ValueNumber)
case ResultTypeError:
return arg
}
}
if numbers[0] < 0 {
return MakeErrorResult("LCM() only accepts positive arguments")
}
if len(numbers) == 1 {
return MakeNumberResult(numbers[0])
}
res := numbers[0]
for i := 1; i < len(numbers); i++ {
if numbers[i] < 0 {
return MakeErrorResult("LCM() only accepts positive arguments")
}
res = lcm(res, numbers[i])
}
return MakeNumberResult(res)
}
// Int is an implementation of the Excel INT() function that rounds a number
// down to an integer.
func Int(args []Result) Result {
if len(args) != 1 {
return MakeErrorResult("INT() requires a single numeric argument")
}
nArg := args[0].AsNumber()
if nArg.Type != ResultTypeNumber {
return MakeErrorResult("INT() requires a single numeric argument")
}
trunc, rem := math.Modf(nArg.ValueNumber)
if rem < 0 {
trunc--
}
return MakeNumberResult(trunc)
}
// Log implements the Excel LOG function which returns the log of a number. By
// default the result is base 10, however the second argument to the function
// can specify a different base.
func Log(args []Result) Result {
if len(args) == 0 {
return MakeErrorResult("LOG() requires at least one numeric argument")
}
if len(args) > 2 {
return MakeErrorResult("LOG() accepts a maximum of two arguments")
}
nArg := args[0].AsNumber()
if nArg.Type != ResultTypeNumber {
return MakeErrorResult("LOG() requires at least one numeric argument")
}
base := 10.0
if len(args) > 1 {
bArg := args[1].AsNumber()
if bArg.Type != ResultTypeNumber {
return MakeErrorResult("LOG() requires second argument to be numeric")
}
base = args[1].ValueNumber
}
if nArg.ValueNumber == 0 {
return MakeErrorResult("LOG() requires first argument to be non-zero")
}
if base == 0 {
return MakeErrorResult("LOG() requires second argument to be non-zero")
}
return MakeNumberResult(math.Log(nArg.ValueNumber) / math.Log(base))
}
func minor(sqMtx [][]Result, idx int) [][]Result {
ret := [][]Result{}
for i := range sqMtx {
if i == 0 {
continue
}
row := []Result{}
for j := range sqMtx {
if j == idx {
continue
}
row = append(row, sqMtx[i][j])
}
ret = append(ret, row)
}
return ret
}
func det(sqMtx [][]Result) float64 {
// two by two
if len(sqMtx) == 2 {
m00 := sqMtx[0][0].AsNumber()
m01 := sqMtx[0][1].AsNumber()
m10 := sqMtx[1][0].AsNumber()
m11 := sqMtx[1][1].AsNumber()
if m00.Type != ResultTypeNumber || m01.Type != ResultTypeNumber ||
m10.Type != ResultTypeNumber || m11.Type != ResultTypeNumber {
return math.NaN()
}
return m00.ValueNumber*m11.ValueNumber -
m10.ValueNumber*m01.ValueNumber
}
res := float64(0)
sgn := float64(1)
for j := range sqMtx {
res += sgn * sqMtx[0][j].ValueNumber * det(minor(sqMtx, j))
sgn *= -1
}
return res
}
// MDeterm is an implementation of the Excel MDETERM which finds the determinant
// of a matrix.
func MDeterm(args []Result) Result {
if len(args) != 1 {
return MakeErrorResult("MDETERM() requires a single array argument")
}
mtx := args[0]
if mtx.Type != ResultTypeArray {
return MakeErrorResult("MDETERM() requires a single array argument")
}
numRows := len(mtx.ValueArray)
for _, row := range mtx.ValueArray {
if len(row) != numRows {
return MakeErrorResult("MDETERM() requires a square matrix")
}
}
return MakeNumberResult(det(mtx.ValueArray))
}
// Mod is an implementation of the Excel MOD function which returns the
// remainder after division. It requires two numeric argumnts.
func Mod(args []Result) Result {
if len(args) != 2 {
return MakeErrorResult("MOD() requires two numeric arguments")
}
n := args[0].AsNumber()
d := args[1].AsNumber()
if n.Type != ResultTypeNumber || d.Type != ResultTypeNumber {
return MakeErrorResult("MOD() requires two numeric arguments")
}
if d.ValueNumber == 0 {
return MakeErrorResultType(ErrorTypeDivideByZero, "MOD() divide by zero")
}
// Per MS page, MOD(n, d) = n - d*INT(n/d)
// where INT is trunc in:
trunc, rem := math.Modf(n.ValueNumber / d.ValueNumber)
if rem < 0 {
trunc--
}
return MakeNumberResult(n.ValueNumber - d.ValueNumber*trunc)
}
// Mround is an implementation of the Excel MROUND function. It is not a
// generic rounding function and has some oddities to match Excel's behavior.
func Mround(args []Result) Result {
if len(args) != 2 {
return MakeErrorResult("MROUND() requires two numeric arguments")
}
// number to round
number := args[0].AsNumber()
if number.Type != ResultTypeNumber {
return MakeErrorResult("first argument to MROUND() must be a number")
}
// significance
significance := float64(1)
sigArg := args[1].AsNumber()
if sigArg.Type != ResultTypeNumber {
return MakeErrorResult("second argument to MROUND() must be a number")
}
significance = sigArg.ValueNumber
if significance < 0 && number.ValueNumber > 0 ||
significance > 0 && number.ValueNumber < 0 {