Vec2 { public Vec2 normalize() { double magnitude = this.magnitude(); if (magnitude != 0) { this.x /= magnitude; this.y /= magnitude; } return this; } Vec2();  Vec2(double x, double y);  Vec2(Vec2 vector); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); float[] toArray(float[] result, int offset); double magnitude(); double magnitudeSquared(); double distanceTo(Vec2 vector); double distanceToSquared(Vec2 vector); Vec2 set(double x, double y); Vec2 set(Vec2 vector); Vec2 swap(Vec2 vector); Vec2 add(Vec2 vector); Vec2 subtract(Vec2 vector); Vec2 multiply(double scalar); Vec2 multiplyByMatrix(Matrix3 matrix); Vec2 divide(double divisor); Vec2 negate(); Vec2 normalize(); double dot(Vec2 vector); Vec2 mix(Vec2 vector, double weight); public double x; public double y; }
@Test public void testNormalize() throws Exception { final double x1 = 3d; final double y1 = 4d; final double length = 5d; Vec2 u = new Vec2(x1, y1); Vec2 v = u.normalize(); double magnitude = u.magnitude(); assertEquals("u.x", (1 / length) * x1, u.x, 1e-15); assertEquals("u.y", (1 / length) * y1, u.y, 1e-15); assertEquals("magnitude", 1.0, magnitude, 1e-15); assertEquals("v == u", u, v); }
@Test public void testNormalize_ReallySmall() throws Exception { Vec2 small = new Vec2(1e-154, 0).normalize(); Vec2 tooSmall = new Vec2(1e-155, 0).normalize(); assertEquals("small: normal = 1.0", 1.0, small.x, 0); assertNotEquals("too small: normal <> 1.0", 1.0, tooSmall.x, 0); }
@Test public void testNormalize_ReallyBig() throws Exception { Vec2 big = new Vec2(1e154, 0).normalize(); Vec2 tooBig = new Vec2(1e155, 0).normalize(); assertEquals("big: normal = 1.0", 1.0, big.x, 0); assertEquals("too big: normal = 0.0", 0.0, tooBig.x, 0); }
@Test public void testNormalize_BigAndSmallComponents() throws Exception { Vec2 extreme = new Vec2(1e154, 1e-154).normalize(); Vec2 tooExtreme = new Vec2(1e155, 1e-155).normalize(); assertEquals("extreme: normal = 1.0", 1.0, extreme.x, 0); assertEquals("too extreme: normal = 0.0", 0.0, tooExtreme.x, 0); }