-
Notifications
You must be signed in to change notification settings - Fork 1
/
eval.go
56 lines (49 loc) · 1.16 KB
/
eval.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
package eval
import (
"math"
"strconv"
)
func evaluateRPN(tokens []string) (float64, error) {
stack := make([]float64, 0, 8)
for _, t := range tokens {
switch t {
case "+":
stack[len(stack)-2] += stack[len(stack)-1]
stack = stack[:len(stack)-1]
case "-":
stack[len(stack)-2] -= stack[len(stack)-1]
stack = stack[:len(stack)-1]
case "*":
stack[len(stack)-2] *= stack[len(stack)-1]
stack = stack[:len(stack)-1]
case "/":
stack[len(stack)-2] /= stack[len(stack)-1]
stack = stack[:len(stack)-1]
case "^":
stack[len(stack)-2] = math.Pow(stack[len(stack)-2], stack[len(stack)-1])
stack = stack[:len(stack)-1]
case "%":
stack[len(stack)-2] %= stack[len(stack)-1]
stack = stack[:len(stack)-1]
default:
f, err := strconv.ParseFloat(t, 64)
if err != nil {
return 0, err
}
stack = append(stack, f)
}
}
return stack[0], nil
}
// Numerical evaluates a numerical mathematical expression and returns the result.
func Numerical(input string) (float64, error) {
rpn, err := infixToRPN(input)
if err != nil {
return 0, err
}
result, err := evaluateRPN(rpn)
if err != nil {
return 0, err
}
return result, nil
}