Find the minimum distance between two lines source codeThis snippet submitted by Giacomo on 2010-07-21. It has been viewed 2958 times.Rating of 6.6 with 9 votes
typedef struct line {
float x0;
float y0;
float z0;
float l;
float m;
float n;
} Line;
double distance(Line line1, Line line2) {
double x01 = line1.x0;
double x02 = line2.x0;
double y01 = line1.y0;
double y02 = line2.y0;
double z01 = line1.z0;
double z02 = line2.z0;
double l1 = line1.l;
double l2 = line2.l;
double m1 = line1.m;
double m2 = line2.m;
double n1 = line1.n;
double n2 = line2.n;
double t1 = (-l1*(pow(m2,2) + pow(n2,2))*(x01 - x02) - (m2*n1 - m1*n2)*(n2*(-y01 + y02) +
m2*(z01 - z02)) + pow(l2,2)*(m1*(-y01 + y02) + n1*(-z01 + z02)) +
l2*(m1*m2*(x01 - x02) + n1*n2*(x01 - x02) + l1*(m2*y01 - m2*y02 + n2*z01 - n2*z02))) /
(pow(l2,2)*(pow(m1,2) + pow(n1,2)) + pow(m2*n1 - m1*n2, 2) - 2*l1*l2*(m1*m2 + n1*n2) + pow(l1,2) * (pow(m2,2) + pow(n2,2)));
double t2 = -((l1*l2 + m1*m2 + n1*n2)*(l1*(x01 - x02) + m1*(y01 - y02) +
n1*(z01 - z02)) - (pow(l1,2) + pow(m1,2) + pow(n1,2))*(l2*(x01 - x02) +
m2*(y01 - y02) + n2*(z01 - z02))) /
(-pow(l1*l2 + m1*m2 + n1*n2, 2) + (pow(l1,2) + pow(m1,2) + pow(n1,2))*(pow(l2,2) + pow(m2,2) + pow(n2,2)));
double p_x = x01 + l1 * t1;
double p_y = y01 + m1 * t1;
double p_z = z01 + n1 * t1;
double q_x = x02 + l2 * t2;
double q_y = y02 + m2 * t2;
double q_z = z02 + n2 * t2;
double dist = sqrt(pow(p_x - q_x, 2) + pow(p_y - q_y, 2) + pow(p_z - q_z,2));
return dist;
}
More C and C++ source code snippets Add a snippet! |