Correct normalization of 0 vector

This commit is contained in:
Fraser Graham 2013-08-08 23:14:18 -07:00
parent a1c37b9235
commit 68842de56e
2 changed files with 12 additions and 0 deletions

View File

@ -58,4 +58,12 @@ func TestNormalize(t *testing.T) {
if vn.Mag() != 1 { if vn.Mag() != 1 {
t.Errorf("Normalize Error") t.Errorf("Normalize Error")
} }
v0 := Vector2d{0, 0}
vn0 := v0.Normalize()
if vn0.Mag() != 0 {
t.Errorf("Normalize Error")
}
} }

View File

@ -44,6 +44,10 @@ func (v Vector2d) Scale(s float64) Vector2d {
} }
func (v Vector2d) Normalize() Vector2d { func (v Vector2d) Normalize() Vector2d {
if v.X == 0 && v.Y == 0 {
return v
}
m := v.Mag() m := v.Mag()
return Vector2d{v.X / m, v.Y / m} return Vector2d{v.X / m, v.Y / m}
} }