Created
January 21, 2014 15:34
-
-
Save kidoman/8542302 to your computer and use it in GitHub Desktop.
Sin kata in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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