Do it with vectors!
Let A, B and C be position vectors of points A, B, C, so AB ( = A - B) is the vector from A to B, and DC (= D - C) is from D to C. Now AB and DC are perpendicular, so their dot product is zero. Let t be the ratio AD/AB (so it's 1 if D is at B, and 0 if it's at A).
These requirements give us:
$$ D = A + tAB $$
$$ (D-C).AB = 0 $$
Solve for t:
$$ (A + tAB - C).AB = 0 $$
$$ (A - C).AB - t(AB.AB) = 0 $$
$$ t = \frac{(A-C).AB}{AB.AB} = \frac{(A-C).AB}{\|AB\|^2}$$
Herewith some Python:
class Vector:
def __init__(self, x, y):
(self.x, self.y) = (x,y)
def sub(self, other):
return Vector( self.x - other.x, self.y - other.y )
def add(self, other):
return Vector( self.x - other.x, self.y - other.y )
def dot(self, other):
return self.x*other.x + self.y*other.y
def scalarMul(self, s):
return Vector( self.x * s, self.y * s )
def intersect(A,B,C):
AB = A.sub(B)
AC = A.sub(C)
t = (AC.dot(AB)) / (AB.dot(AB))
return A.add(AB.scalarMul(t))
A=Vector(4.5, 0.5)
B=Vector(0.5, 1.5)
C=Vector(1.5, 0.5)
D=intersect(A,B,C)
print D.x, D.y