LineEquation.java
package ac.essex.ooechs.imaging.commons.util;
/**
* Finds the equation of a line. Once two line equations are found, the
* intersection between them can be discovered.
*/
public class LineEquation implements Comparable {
protected double m, c;
public static void main(String[] args) {
LineEquation l1 = new LineEquation(-3, -3, 4, 4);
LineEquation l2 = new LineEquation(-4, 4, 3, 0);
l1.getIntersectionWith(l2);
}
public LineEquation(double m, double c) {
this.m = m;
this.c = c;
}
public LineEquation(double x1, double y1, double x2, double y2) {
if (x1 == x2) {
throw new RuntimeException("Cannot calculate line equation - x1 and x2 values must be different");
}
double dx = x2 - x1;
double dy = y2 - y1;
m = dy / dx;
c = y1 - (m * x1);
}
/**
* Returns the intersection between two line equations.
* @param other Another line equation.
* @return
*/
public double[] getIntersectionWith(LineEquation other) {
double x = (other.c - c) / (m - other.m);
double y1 = getY(x);
return new double[]{x, y1};
}
public void setM(double m) {
this.m = m;
}
public void setC(double c) {
this.c = c;
}
public double getM() {
return m;
}
public double getC() {
return c;
}
public double getY(double x) {
return (m * x) + c;
}
public double getX(double y) {
return (y - c) / m;
}
/**
* Returns a metric of how similar the two line equations are.
* @param other
* @return
*/
public double getSimilarity(LineEquation other) {
double dm = Math.abs(other.m - m) / Math.max(Math.abs(other.m), Math.abs(m));
double dc = Math.abs(other.c - c) / Math.max(Math.abs(other.c), Math.abs(c));
return dm + dc;
}
public LineEquation getPerpendicular() {
return new LineEquation(-1/m, c);
}
public int compareTo(Object o) {
LineEquation other = (LineEquation) o;
if (other.c > c) return +1;
if (other.c < c) return -1;
return 0;
}
}