-
Notifications
You must be signed in to change notification settings - Fork 15
/
math_funcs.go
108 lines (96 loc) · 2.04 KB
/
math_funcs.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
package fmr
import (
"fmt"
"math"
"math/big"
"strconv"
)
func init() {
builtinFuncs["nf.math.sum"] = sum
builtinFuncs["nf.math.sub"] = sub
builtinFuncs["nf.math.mul"] = mul
builtinFuncs["nf.math.div"] = div
builtinFuncs["nf.math.pow"] = pow
builtinFuncs["nf.math.neg"] = neg
builtinFuncs["nf.math.even"] = even
builtinFuncs["nf.math.odd"] = odd
builtinFuncs["nf.math.prime"] = prime
}
func sum(x, y string) string {
return calc(x, y, "Add")
}
func sub(x, y string) string {
return calc(x, y, "Sub")
}
func mul(x, y string) string {
return calc(x, y, "Mul")
}
func div(x, y string) string {
fx, err := strconv.ParseFloat(x, 64)
if err != nil {
return fmt.Sprintf("%s/%s", x, y)
}
fy, err := strconv.ParseFloat(y, 64)
if err != nil || fy == 0 {
return fmt.Sprintf("%s/%s", x, y)
}
return fmt.Sprintf("%f", fx/fy)
}
func pow(x, y string) string {
fx, err := strconv.ParseFloat(x, 64)
if err != nil {
return fmt.Sprintf("%s^%s", x, y)
}
fy, err := strconv.ParseFloat(y, 64)
if err != nil {
return fmt.Sprintf("%s^%s", x, y)
}
return fmt.Sprintf("%f", math.Pow(fx, fy))
}
func neg(x string) string {
xf := new(big.Float)
if _, err := fmt.Sscan(x, xf); err != nil {
return ""
}
return xf.Neg(xf).String()
}
func even(x string) string {
xi := new(big.Int)
if _, err := fmt.Sscan(x, xi); err == nil && xi.Bit(0) == 0 {
return "true"
}
return "false"
}
func odd(x string) string {
xi := new(big.Int)
if _, err := fmt.Sscan(x, xi); err == nil && xi.Bit(0) == 1 {
return "true"
}
return "false"
}
func prime(x string) string {
xi := new(big.Int)
if _, err := fmt.Sscan(x, xi); err == nil && xi.ProbablyPrime(10) {
return "true"
}
return "false"
}
func calc(x, y, method string) string {
xf, yf := new(big.Float), new(big.Float)
if _, err := fmt.Sscan(x, xf); err != nil {
return ""
}
if _, err := fmt.Sscan(y, yf); err != nil {
return ""
}
switch method {
case "Add":
return xf.Add(xf, yf).String()
case "Sub":
return xf.Sub(xf, yf).String()
case "Mul":
return xf.Mul(xf, yf).String()
default:
return ""
}
}