diff options
| author | Sam Anthony <sam@samanthony.xyz> | 2023-07-29 11:19:55 -0230 |
|---|---|---|
| committer | Sam Anthony <sam@samanthony.xyz> | 2023-07-29 11:19:55 -0230 |
| commit | 008e4021375883610cf1b07e005a4176acadc0de (patch) | |
| tree | 3148bbf1945c8e0517810ea234e16c498f968eb4 /func.go | |
| parent | c12813975d7529f864199b876bc3ee3b470c1c18 (diff) | |
| download | pfc-008e4021375883610cf1b07e005a4176acadc0de.zip | |
trig functions
Diffstat (limited to 'func.go')
| -rw-r--r-- | func.go | 50 |
1 files changed, 41 insertions, 9 deletions
@@ -1,18 +1,50 @@ package main -import "math" +import ( + "fmt" + "math" +) -// parseFunction returns nil is s is not a valid function. -func parseFunction(s string) func(Stack) { - switch s { - case "sin": - return sin +// parseFunction returns nil is fn is not a valid function. +func parseFunction(fn string) func(Calculator) { + switch fn { + case "sin", "cos", "tan": + return trig(fn) } return nil } -func sin(stack Stack) { - if len(stack) > 0 { - stack[len(stack)-1] = math.Sin(stack[len(stack)-1]) +// trig returns a closure that performs the trig function specified by fn. +// Panics if fn is not one of "sin", "cos" or "tan". +func trig(fn string) func(Calculator) { + return func(c Calculator) { + if len(c.stack) <= 0 { + return + } + v := &c.stack[len(c.stack)-1] + // The math package expects arguments to trig functions to be in radians. + if c.anglem == modeDeg { + *v = radians(*v) + } + switch fn { + case "sin": + *v = math.Sin(*v) + case "cos": + *v = math.Cos(*v) + case "tan": + *v = math.Tan(*v) + default: + panic(fmt.Sprintf("invalid trig function: '%s'", fn)) + } } } + +// radians converts degrees to radians. +func radians(deg float64) float64 { + return deg * math.Pi / 180.0 +} + +// degrees converts radians to degrees. +func degrees(rad float64) float64 { + return rad * 180 / math.Pi +} |