Intercept implements Scalar<T> { @Override public T value(final Field<T> field) { if (!new Vertical<>(this.line).resolve(field)) { final Scalar<T>[] coords = this.line.point().coords(); final Scalar<T> slope = new Slope<>(this.line); return field.actual( new Diff<T>(coords[1], new Multiplication<>(slope, coords[0])) ); } throw new IllegalStateException( "Line has infinite slope. Could not calculate y-intercept." ); } Intercept(final Line<T> line);  Intercept(final Ray<T> ray);  Intercept(final Segment<T> seg); @Override T value(final Field<T> field);  }
@Test public void calculatesIntercept() { final Line<Double> line = new RandomLine<>(); final double error = 1.e-6; final Decimal dec = new Decimal(); final Double startx = line.point().coords()[0].value(dec); final Double starty = line.point().coords()[1].value(dec); final Double dirx = line.direction().coords()[0].value(dec); final Double diry = line.direction().coords()[1].value(dec); MatcherAssert.assertThat( new Intercept<Double>(line).value(dec), Matchers.closeTo(starty - startx * diry / dirx, error) ); }
@Test public void calculatesRayIntercept() { final Ray<Double> ray = new PtDirRay<>(new RandomPoint<>(), new RandomPoint<>()); final double error = 1.e-6; final Decimal dec = new Decimal(); final Double startx = ray.origin().coords()[0].value(dec); final Double starty = ray.origin().coords()[1].value(dec); final Double dirx = ray.direction().coords()[0].value(dec); final Double diry = ray.direction().coords()[1].value(dec); MatcherAssert.assertThat( new Intercept<Double>(ray).value(dec), Matchers.closeTo(starty - startx * diry / dirx, error) ); }
@Test public void calculatesSegmentIntercept() { final Segment<Double> seg = new PtVectSegment<>(new RandomPoint<>(), new RandomPoint<>()); final double error = 1.e-6; final Decimal dec = new Decimal(); final Double startx = seg.start().coords()[0].value(dec); final Double starty = seg.start().coords()[1].value(dec); final Double endx = seg.end().coords()[0].value(dec); final Double endy = seg.end().coords()[1].value(dec); MatcherAssert.assertThat( new Intercept<Double>(seg).value(dec), Matchers.closeTo( starty - startx * (endy - starty) / (endx - startx), error ) ); }
@Test public void errorsWhenVerticalLine() { this.thrown.expect(IllegalStateException.class); final Line<Double> line = new VerticalLine<>(); new Intercept<>(line).value(new Decimal()); }