Skip to content

Instantly share code, notes, and snippets.

@kidoman kidoman/sin.go
Created Jan 21, 2014

Embed
What would you like to do?
Sin kata in Go
package main
const accuracy = 0.00001
func multiplier(i int, angle, num, den float64) (float64, float64) {
num *= angle * angle
den *= float64(i * (i - 1))
return num, den
}
func sin(angle float64) float64 {
sign := 1.0
val := angle
num, den := angle, 1.0
for i := 3; ; i += 2 {
sign *= -1
num, den = multiplier(i, angle, num, den)
term := num / den
if term < accuracy {
break
}
val += sign * term
}
return val
}
package main
import (
"math"
"testing"
)
var sinValues = []struct {
rad, val float64
}{
{0.0, 0.0},
{math.Pi / 2, 1},
{math.Pi / 4, 1 / math.Sqrt2},
{math.Pi, 0},
}
func compare(x, y float64) bool {
if math.Abs(x-y) < accuracy {
return true
}
return false
}
func TestSineVal(t *testing.T) {
for _, d := range sinValues {
if val := sin(d.rad); !compare(val, d.val) {
t.Errorf("Expected sin(%v) to be %v but got %v", d.rad, d.val, val)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.