Adding Normalize

This commit is contained in:
Fraser Graham 2013-08-08 23:08:22 -07:00
parent ace1638310
commit a1c37b9235
2 changed files with 20 additions and 6 deletions

View File

@ -9,13 +9,13 @@ func TestSubMag(t *testing.T) {
p1 := Point2d{10, 10} p1 := Point2d{10, 10}
p2 := Point2d{7, 6} p2 := Point2d{7, 6}
v := p1.sub(p2) v := p1.Sub(p2)
if v != (Vector2d{3, 4}) { if v != (Vector2d{3, 4}) {
t.Errorf("Sub Error") t.Errorf("Sub Error")
} }
m := v.mag() m := v.Mag()
if m != 5 { if m != 5 {
t.Errorf("Mag Error") t.Errorf("Mag Error")
@ -24,17 +24,17 @@ func TestSubMag(t *testing.T) {
func TestScale(t *testing.T) { func TestScale(t *testing.T) {
v := Vector2d{3, 4} v := Vector2d{3, 4}
m := v.mag() m := v.Mag()
if m != 5 { if m != 5 {
t.Errorf("Mag Error") t.Errorf("Mag Error")
} }
m2 := v.scale(2) m2 := v.Scale(2)
fmt.Printf("%v\n", m2) fmt.Printf("%v\n", m2)
if m2.mag() != 10 { if m2.Mag() != 10 {
t.Errorf("Mag Error") t.Errorf("Mag Error")
} }
} }
@ -42,7 +42,7 @@ func TestScale(t *testing.T) {
func TestAdd(t *testing.T) { func TestAdd(t *testing.T) {
p := Point2d{10, 10} p := Point2d{10, 10}
v := Vector2d{3, 4} v := Vector2d{3, 4}
m := p.add(v) m := p.Add(v)
fmt.Printf("%v\n", m) fmt.Printf("%v\n", m)
@ -50,3 +50,12 @@ func TestAdd(t *testing.T) {
t.Errorf("Add Error") t.Errorf("Add Error")
} }
} }
func TestNormalize(t *testing.T) {
v := Vector2d{3, 4}
vn := v.Normalize()
if vn.Mag() != 1 {
t.Errorf("Normalize Error")
}
}

View File

@ -42,3 +42,8 @@ func (v Vector2d) PopPop() float64 {
func (v Vector2d) Scale(s float64) Vector2d { func (v Vector2d) Scale(s float64) Vector2d {
return Vector2d{v.X * s, v.Y * s} return Vector2d{v.X * s, v.Y * s}
} }
func (v Vector2d) Normalize() Vector2d {
m := v.Mag()
return Vector2d{v.X / m, v.Y / m}
}