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
on 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.