7

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.

William the Coderer
  • 708
  • 1
  • 7
  • 19

5 Answers5

14

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.

andand
  • 17,134
  • 11
  • 53
  • 79
  • Yes, that is it... The simpler algorithm worked good for two points, so I figured it would therefor work for a line (since a line is described by two points). Thanks – William the Coderer Nov 11 '11 at 06:31
2

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

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
2

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

legiero
  • 374
  • 1
  • 8
2

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

chx
  • 11,270
  • 7
  • 55
  • 129
1

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.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358