Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple math algorithm: Center point of a line

I have an algorithm as follows for finding the center of a line (midpoint).

public DoublePoint getMidPoint() {
    return new DoublePoint((origin.x + endPoint.x) / 2, (origin.y + endPoint.y) / 2);
}

It seems to work for any values. But I seem to remember a much more complex algorithm, involving two circles whose radius equals the length of the line and whose center points are the ends of the line. A line drawn from the intersection of those circles would intersect the line segment you are testing, giving the line's midpoint. I know for sure that algorithm works 100% of the time. Not sure about my simpler algorithm which seems too simple.

like image 555
William the Coderer Avatar asked Nov 11 '11 06:11

William the Coderer


5 Answers

What you are remembering is a geometric method of constructing the perpendicular bisector of a line segment using only a compass and straightedge. Consider, for instance:

enter image description here

This was fine for the ancient Greeks, but there are other methods (such as the one you have coded) which work better for computers.

like image 137
andand Avatar answered Nov 15 '22 07:11

andand


Your simple algoritm is full correct. Method with circles is a finding the midpoint with pair of compasses.

like image 20
legiero Avatar answered Nov 15 '22 06:11

legiero


The algorithm you vaguely remember is to use a straightedge and a compass to get the midpoint. Draw take two equal radius circles centered on the two ends of the line segment in such way that they intersect -- the length of the line segment will do. Use the straightedge to connect the points where the circles intersect. Where this line intersects the original line segment is the midpoint. Fancy animation at http://www.mathopenref.com/constbisectline.html

like image 31
chx Avatar answered Nov 15 '22 06:11

chx


The algorithm and code you have is the simplest and best way to do this.

like image 28
David Heffernan Avatar answered Nov 15 '22 06:11

David Heffernan


Your algorithm is a simplification of translating the line to the origin, finding the vector represented by that line, halving it, then translating it back to the original line. The simplification is valid, and the algorithm is correct.

like image 45
Ignacio Vazquez-Abrams Avatar answered Nov 15 '22 08:11

Ignacio Vazquez-Abrams