Algorithm for reflecting a point across a line

With reference to the fig in here.

We want to find the reflection of the point A(p,q) to line L1,eqn y = m*x + c. Say reflected point is A'(p',q')

Suppose, The line joining the points A and A' is L2 with eqn: y= m'*x + c' L1 & L2 intersect at M(a,b)

The algorithm for finding the reflection of the point is as follows: 1) Find slope of L2 is = -1/m , as L1 and L2 are perpendicular 2) Using the m' and A(x,y) find c' using eqn of L2 3) Find the intersection point 'M' of L1 anSd L2 4) As now we have coordinate of A and M so coordinate of A' can be easily obtained using the relation [ A(p,q)+A'(p',q') ]/2 = M(a,b)

I haven't checked the following code but the crude form of code in the FORTRAN is

SUBROUTINE REFLECTION(R,p,q)

IMPLICIT NONE

REAL,INTENT(IN)     ::  p,q

REAL, INTENT(OUT)   ::  R(2)

REAL                ::  M1,M2,C1,C2,a,b

M2=-1./M1                       ! CALCULATE THE SLOPE OF THE LINE L2 

C2=S(3,1)-M2*S(3,2)             ! CALCULATE THE 'C' OF THE LINE L2  

q= (M2*C1-M1*C2)/(M2-M1)        ! CALCULATE THE MID POINT O

p= (q-C1)/M1

R(1)=2*a-p                      ! GIVE BACK THE REFLECTION POINTS COORDINATE

R(2)=2*b-q

END SUBROUTINE REFLECTION

This is a simple explanation of Il-Bhima's solution. The trick is to notice that what you want is to project that point orthogonally on the line, move it by that much, and then move it once again, in the same direction.

For these types of problems, it's easier to work with a slightly more redundant representation for a line. Instead of y = m x + b, let's represent the line by a point p that is on the line and a vector d in the line's direction. Let's call this point p = (0, b), the vector d = (1, m), and your input point will be p1. The projected point on the line will be pl and your output point p2, then, is p1 + 2 * (pl - p1) = 2 * pl - p1

The formula you need here is the projection of a vector v onto a line which goes through the origin in direction d. It is given by d * <v, d> / <d, d> where <a, b> is the dot product between two vectors.

To find pl, we have to move the whole problem so that the line goes through the origin by subtracting p from p1, using the above formula, and moving it back. Then, pl = p + (d * <p - p1, d> / <d, d>), so pl_x = p_x + (b * p1_x) / (1 + m * m), pl_y = p_y + (m * p1_x) / (1 + m * m), and then use p2 = 2 * pl - p1 to get the final values.


Ok, I'm going to give you a cookbook method to do this. If you're interested in how I derived it, see http://www.sdmath.com/math/geometry/reflection_across_line.html#formulasmb

Given point (x1, y1) and a line that passes through (x2,y2) and (x3,y3), we can first define the line as y = mx + c, where:

slope m is (y3-y2)/(x3-x2)

y-intercept c is (x3*y2-x2*y3)/(x3-x2)

If we want the point (x1,y1) reflected through that line, as (x4, y4), then:

set d = (x1 + (y1 - c)*m)/(1 + m^2) and then:

x4 = 2*d - x1
y4 = 2*d*m - y1 + 2*c