问题
I have a piece of code that checks if the given 3 coordinates are linear to one another (if so, return true). But is there a way to make the code give or take a few pixels/plots?
private boolean collinear(double x1, double y1, double x2, double y2, double x3, double y3) {
return (y1 - y2) * (x1 - x3) == (y1 - y3) * (x1 - x2);
}
You see, the coordinates have to be exactly inline for it to register as linear. How will I be able to make it look within a 'range' of some kind, for it to check within a value, and then to then set the coordinates with the new value?
---- Added ----
I'm trying to see if the 3 points make a linear line, but I want it to check within a threshold (as some points maybe off by a little). Once the Java has found that in fact the points are linear (give or take), I want it to then replace the x1, x2, x3, y1 ect ... with what the value would have been that Java checked against.
回答1:
Using the Hesse Normal Form you can calculate the perpendicular distance from a point to a line. So when the distance is smaller than a treshhold, they are sufficiently near.
Such code is called distanceFromLine
()
Java has that built in
Line2D line = new Line2D.Double(x0, y0, x1, y1);
double distance = line.ptLineDist(px, py);
if (Math.abs(distance) < threshold) {
// is Near line
}
回答2:
Are you looking for a tolerance meeting some specific formula, or just in general, "close"?
If you're just looking for a general "close", then just check for difference within some useful range instead of equal. e.g.
return Math.abs((x1-x2)*(y1-y3)-(y1-y2)*(x1-x3))<tolerance;
If you have some specific rule, like "the third point must be within 2 pixels of the line formed by the first two points" or some such, then of course you'd have to study whatever rule and write code that explicitly implements it.
来源:https://stackoverflow.com/questions/13591837/java-average-linear-graph-plots