I'm looking to find the intersect of 2 lines using Cramer's rule. This is for an exercise from the book An Introduction To Java Programming (Exercise 3.25 from Chapter 3 and 8.31 from Chapter 8. They are both basically the same idea just the one from chapter 8 uses arrays).
The exercise tells us to use Cramer's Rule and provides the general formula.
(y1 - y2)x - (x1 - x2)y = (y1 - y2)x1 - (x1 - x2)y1
(y3 - y4)x - (x3 - x4)y = (y3 - y4)x3 - (x3 - x4)y3
My problem is that I'm getting the y coordinate as a negative while I expected it to be a positive.
This is the output that I'm getting.
The intersecting point is at (2.888888888888889, -1.1111111111111112)
This is what I expected to get.
The intersecting point is at (2.888888888888889, 1.1111111111111112)
Here is the code I have come up with.
public class Test{
public static void main(String[] args){
double[][] points = {{2, 2}, {5, -1.0}, {4.0, 2.0}, {-1.0, -2.0}};
double[] result = getIntersectingPoint(points);
if(result == null)
System.out.println("The 2 lines are parallel");
else
System.out.println("The intersecting point is at (" + result[0] + ", " + result[1] + ")");
}
/*
*For two lines to see if they intersect
*(y1 - y2)x - (x1 - x2)y = (y1 - y2)x1 - (x1 - x2)y1
*(y3 - y4)x - (x3 - x4)y = (y3 - y4)x3 - (x3 - x4)y3
*/
public static double[] getIntersectingPoint(double[][] points){
double[] result = new double[2];
double a = points[0][1] - points[1][1]; //y1 - y2;
double b = points[0][0] - points[1][0]; //x1 - x2;
double c = points[2][1] - points[3][1]; //y3 - y4;
double d = points[2][0] - points[3][0]; //x3 - x4;
double e = a * points[0][0] - b * points[0][1]; //(y1 - y2)x1 - (x1 - x2)y1
double f = c * points[2][0] - d * points[2][1]; //(y3 - y4)x3 - (x3 - x4)y3
double determinant = a * d - b * c;
//There is no solution to the equation,
//this shows the lines are parallel
if(determinant == 0)
return null;
//There is a solution to the equation
//this shows the lines intersect.
else{
result[0] = (e * d - b * f) / determinant;
result[1] = (a * f - e * c) / determinant;
}
return result;
}
}
I have searched around and found some solutions in general to the exercise. But I haven't found anything about my issue of getting a negative y coordinate.
To answer my own question...
I finally figured out the problem. At the end of the function getIntersectingPoint
there us the following line.
result[0] = (e * d - b * f) / determinant;
this needs to be changed to the following.
result[0] = (b * f - e * d) / determinant;
A little in my defense. I don't really understand Cramer's rule, I was just following what the book was telling me. the book shows the following as the rule. (This is given in Chapter 1 Exercise 1.13).
ax + by = e
cx + dy = f
x = ed - bf / ad - bc
y = af - ec / ad - bc
Given this I just adjusted it to find the line intersect.