Geometry: Steven Skiena
Geometry: Steven Skiena
Geometry: Steven Skiena
Geometry
Steven Skiena
http://www.cs.sunysb.edu/∼skiena
Geometry
This chapter will deal with programming problems associated
with “real” geometry – lines, points, circles, and so forth.
Although you did geometry in high school, it can be
surprisingly difficult to program even very simple things. One
reason is that floating point arithmetic introduces numerical
uncertainty.
Another difficulty of geometric programming is that certain
“obvious” operations you do with a pencil, such as finding the
intersection of two lines, requires non-trivial programming to
do correctly with a computer.
Degeneracy
Special cases or degeneracies require extra attention when
doing geometric programming. For these reasons I recom-
mend you carefully study my code fragments before writing
your own.
There is more geometry to come next week, when we con-
sider problems associated with line segments and polygons a
field known as computational geometry,
Lines
Straight lines are the shortest distance between any two
points. Lines are of infinite length in both directions, as
opposed to line segments, which are finite. We limit our
discussion here to lines in the plane.
Every line l is completely represented by any pair of points
(x1, y1) and (x2, y2) which lie on it.
Lines are also completely described by equations such as
y = mx + b, where m is the slope of the line and b is the
y-intercept, i.e., the unique point (0, b) where it crosses the
x-axis.
Line Type
Vertical lines cannot be described by such equations, how-
ever, because dividing by ∆x means dividing by zero. The
equation x = c denotes a vertical line that crosses the x-axis
at the point (c, 0).
We use the more general formula ax + by + c = 0 as the
foundation of our line type because it covers all possible lines
in the plane:
typedef struct {
double a; /* x-coefficient */
double b; /* y-coefficient */
double c; /* constant term */
} line;
Multiplying these coefficients by any non-zero constant
yields an alternate representation for any line. We establish
a canonical representation by insisting that the y-coefficient
equal 1 if it is non-zero. Otherwise, we set the x-coefficient
to 1:
points_to_line(point p1, point p2, line *l)
{
if (p1[X] == p2[X]) {
l->a = 1;
l->b = 0;
l->c = -p1[X];
} else {
l->b = 1;
l->a = -(p1[Y]-p2[Y])/(p1[X]-p2[X]);
l->c = -(l->a * p1[X]) - (l->b * p1[Y]);
}
}
if (parallelQ(l1,l2) == TRUE) {
printf("Error: Distinct parallel lines do not intersect.\n");
return;
}