Bent Hansen
Bent Hansen

Reputation: 55

What is an algorithm to find intersection of two linear equations?

I'm struggling to figure out an algorithm to find the intersection of two linear equations like:

f(x)=2x+4

g(x)=x+2

I'd like to use the method where you set f (x)=g (x) and solve x, and I'd like to stay away from cross product.

Does anyone have any suggestion to how an algorithm like that would look like?

Upvotes: 3

Views: 2590

Answers (4)

displayName
displayName

Reputation: 14379

If your input lines are in slope-intercept form, an algorithm is an over-kill as there is a direct formula to calculate their point of intersection. It's given on a Wikipedia page and you can understand it as explained below.

Given the equations of the lines: The x and y coordinates of the point of intersection of two non-vertical lines can easily be found using the following substitutions and rearrangements.

Suppose that two lines have the equations y = ax + c and y = bx + d where a and b are the slopes (gradients) of the lines and where c and d are the y-intercepts of the lines. At the point where the two lines intersect (if they do), both y coordinates will be the same, hence the following equality:

ax + c = bx + d.

We can rearrange this expression in order to extract the value of x,

ax - bx = d - c, and so,

x = (d-c)/(a-b).

To find the y coordinate, all we need to do is substitute the value of x into > either one of the two line equations. For example, into the first:

y=(a*(d-c)/(a-b))+c.

Hence, the Point of Intersection is {(d-c)/(a-b), (a*(d-c)/(a-b))+c}

Note: If a = b then the two lines are parallel. If c ≠ d as well, the lines are different and there is no intersection, otherwise the two lines are identical.

Upvotes: 6

A.S.H
A.S.H

Reputation: 29332

General solution. Let

f(x) = a1x + b1 ....... g(x) = a2x + b2

Special cases:

  • a1 == a2 and b1 == b2 : lines coincide

  • a1 == a2 and b1 != b2 : lines are parallel, no intersection

General case: a1 != a2

X = (b2 - b1) / (a1 - a2) ....and... Y = (a1b2 - a2b1) / (a1 - a2)

Upvotes: 1

tuxedobob
tuxedobob

Reputation: 211

Given: ax + b = cx + d

ax = cx + d - b

ax - cx = d - b

x(a - c) = d - b

Therefore, x = (d - b) / (a - c)

In your example, let a = 2, b = 4, c = 1 d = 2

x = (2 - 4) / (2 - 1)

x = -2 / 1

x = -2

Upvotes: 3

tar
tar

Reputation: 1568

I don't remember what cross products are in the context of equations.

One way to solve these is to set them equal to each other, solve for x, then use that value to solve for y:

2x + 4 = x + 2
2x + 2 = x
     x = -2
     y = f(x)
       = g(x)
       = x + 2
       = -2 + 2
       = 0

Solution: (-2, 0)

Upvotes: 0

Related Questions