Segment { public double distance(final Vector2D p) { final double deltaX = end.getX() - start.getX(); final double deltaY = end.getY() - start.getY(); final double r = ((p.getX() - start.getX()) * deltaX + (p.getY() - start.getY()) * deltaY) / (deltaX * deltaX + deltaY * deltaY); if (r < 0 || r > 1) { final double dist1 = getStart().distance((Point<Euclidean2D>) p); final double dist2 = getEnd().distance((Point<Euclidean2D>) p); return FastMath.min(dist1, dist2); } else { final double px = start.getX() + r * deltaX; final double py = start.getY() + r * deltaY; final Vector2D interPt = new Vector2D(px, py); return interPt.distance((Point<Euclidean2D>) p); } } Segment(final Vector2D start, final Vector2D end, final Line line); Vector2D getStart(); Vector2D getEnd(); Line getLine(); double distance(final Vector2D p);  }
@Test public void testDistance() { Vector2D start = new Vector2D(2, 2); Vector2D end = new Vector2D(-2, -2); Segment segment = new Segment(start, end, new Line(start, end, 1.0e-10)); Assert.assertEquals(FastMath.sqrt(2), segment.distance(new Vector2D(1, -1)), 1.0e-10); Assert.assertEquals(FastMath.sin(Math.PI / 4.0), segment.distance(new Vector2D(0, -1)), 1.0e-10); Assert.assertEquals(FastMath.sqrt(8), segment.distance(new Vector2D(0, 4)), 1.0e-10); Assert.assertEquals(FastMath.sqrt(8), segment.distance(new Vector2D(0, -4)), 1.0e-10); }