diff options
| author | Sam Anthony <sam@samanthony.xyz> | 2023-09-16 18:05:52 -0400 |
|---|---|---|
| committer | Sam Anthony <sam@samanthony.xyz> | 2023-09-16 18:05:52 -0400 |
| commit | d58154ad35ab1e0b0d9d520419b08fe8565b7b2c (patch) | |
| tree | 91b30a5d4ace8a6fef16698180226789deed3dc2 | |
| parent | c45883174aa26f9032f2c35867149971bf019525 (diff) | |
| download | pfc-d58154ad35ab1e0b0d9d520419b08fe8565b7b2c.zip | |
factorial function
| -rw-r--r-- | func.go | 20 |
1 files changed, 20 insertions, 0 deletions
@@ -16,6 +16,8 @@ func parseFunction(fn string) func(Calculator) { return deg case "rad": return rad + case "fac": + return fac } return nil } @@ -69,18 +71,36 @@ func invTrig(fn string) func(Calculator) { } } +// Convert radians to degrees. func deg(c Calculator) { if len(c.stack) > 0 { c.stack[len(c.stack)-1] = degrees(c.stack[len(c.stack)-1]) } } +// Convert degrees to radians. func rad(c Calculator) { if len(c.stack) > 0 { c.stack[len(c.stack)-1] = radians(c.stack[len(c.stack)-1]) } } +// Factorial (!). +func fac(c Calculator) { + if len(c.stack) > 0 { + a := &c.stack[len(c.stack)-1] // will replace with a! + if float64(int(*a)) != *a { // undefined on non-ints + return + } else if int(*a) == 0 { // 0! = 1 + *a = 1.0 + } else { // a! = a*(a-1)! + for i := int(*a) - 1; i > 1; i-- { + *a *= float64(i) + } + } + } +} + // radians converts degrees to radians. func radians(deg float64) float64 { return deg * math.Pi / 180.0 |