B
B
Biaci_Anj2021-11-28 04:44:50
Java
Biaci_Anj, 2021-11-28 04:44:50

Check if the segments intersect, what am I doing wrong?

The program must determine where the segments are cut off, if they are not cut off, then return null.
Unfortunately, the method does not work with some segments, for example, with what is now indicated in it.
I would be very grateful if you help me understand how to edit the condition.
Point intersection() {
double x1 = 0; // first line start
double y1 = 0;

double x2 = 1; // first line end
double y2 = 1;

double x3 = -1; // second line start
double y3 =-1;

double x4 = -2; // second line end
double y4 = 2;

if (x1 >= x2) {
double temp;
temp=x1;
x1 = x2;
x2 = temp;

temp=y1;
y1 = y2;
y2=temp;
}
if (x3 >= x4) {
double temp;
temp=x3;
x3 = x4;
x4 = temp;

temp=y3;
y3 = y4;
y4=temp;
}

double k1;
if (y2 == y1) k1 = 0;
else {
k1 = (y2-y1) / (x2-x1);
}
double k2;
if (y3 == y4) k2 = 0;
else {
k2 = (y4 - y3) / (x4 - x3);
}
if (k1 == k2) return null; // parallel

double b1 = y1 - k1 * x1;
double b2 = y3 - k2 * x3;

if (b1 == b2) return new Point(0, b1);
double leftPart = k1 + -k2;
double rightPart = b2 + -b1;
double x = rightPart/leftPart;
double y = k1 * x + b1;

return newPoint(x, y);
}

Another example of a segment that gives the wrong result:
Start x 0, y 3
End x 4, y 0

AND
Start x -1. y -3
end x 1, y 1

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AlexHell, 2021-12-02
@AlexHell

Wikipedia has a formula and explanations https://en.wikipedia.org/wiki/Intersection_(Euclid...
but according to your code, I didn’t exactly understand it in
brief as it should:
* equations of lines are created through 2 points
* intersections of two equations of lines are checked - there are whether the intersection point (may not be)
* checking whether the intersection point belongs to each segment (either explicitly or better parametrically) (may be in the equation but not in the range of the segment)
however, this cannot be done because of the error double if (y2 == y1) k1 = 0 ; usually checked via if(Abs(y2 - y1) < epsilon) (let's say 0.0001 but depends on tasks)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question