March 1, 2007

Mínima distância entre um ponto e uma recta

No seguimento do post anterior ( e especialmente para ti ó sleeper ) apresento-vos o fantástico algoritmo de cálculo de distância entre um ponto e uma recta

Mostra/Oculta LineMagnitude


double lineMagnitude(double x1, double y1, double z1,
double x2, double y2, double z2)
{
return Math.Sqrt(
Math.Pow((x2 - x1),2) +
Math.Pow((y2 - y1),2) +
Math.Pow((z2 - z1),2)
)
}

Mostra/Oculta DistancePointLine



/// px,py,pz point to test
/// x1,y1,z1, x2,y2,z2 line segment
///
/// Returns distance from the line, or if the intersecting
/// point on the line nearest the point tested is outside
/// the endpoints of the line, the distance to the nearest
/// endpoint.
/// Returns double.NegativeInfinity on 0 denominator conditions.

double DistancePointLine(double px, doubel py, doubel pz,
double x1 , double y1, double z1,
double x2,double y2, double z2 )

{
double LineMag, u;
double ix , iy; // intersecting point

LineMag = lineMagnitude(x1, y1, z1, x2, y2, z2);

if( 0.0 > LineMag)
return double.NegativeInfinity;

u = (((px - x1) * (x2 - x1)) + ((py - y1) * (y2 - y1)) +
((pz - z1) * (z2 - z1)));
u = u / (LineMag * LineMag);
if(u != 1)
{
// closest point does not fall within the line segment
// take the shorter distance to an endpoint
ix = lineMagnitude(px, py, x1, y1);
iy = lineMagnitude(px, py, x2, y2);
return ( (iy < ix)? iy : ix);
}
else
{
//Intersecting point is on the line, use the formula
ix = x1 + u * (x2 - x1);
iy = y1 + u * (y2 - y1);
iz = z1 + u * (z2 - z1);
return lineMagnitude(px, py, pz, ix, iy, iz);
}
}



Nota: Os cálculos assumem que os dados de entrada já vêem no sistema de unidades métrico, caso isso não seja um facto o cálculo devolve valores num sistema de unidades algo complexo, logo se for utilizado o post anterior para cálculo de distâncias temos uma solução bastante completa no que diz respeito a cálculos entre distâncias e posicionamentos.

1 comment:

Bruno Silva said...

Estou 1 bocadito confuso, pq as funções que eu tenho são apenas de converter pixeis em latitude e vice-versa.

A mim dava-me era bastante jeito saber como usar o Virtual Earth sem ter que usar o Controlo de javascript k a MS suporta, queria ir buscar os dados directamente, se alguem souber como, apite :D