Skip to content

Instantly share code, notes, and snippets.

@juanfal
Created October 19, 2014 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanfal/cf6e1d65bc2e8c3df7d7 to your computer and use it in GitHub Desktop.
Save juanfal/cf6e1d65bc2e8c3df7d7 to your computer and use it in GitHub Desktop.
cálculo de la distancia de un punto (xp,yp) a un segmento (no recta), (x1,y1)-(x2,y2) de pendiente 1. Es muy preciso, da resultado real. Falta simplificar-optimizar y considerar el caso de pendiente -1
// distPsegm.cpp
// juanfc 2014-10-19
// Distancia de un punto (xp, yp) a una recta de pendiente 1
// El resultado se da como número real. Si se quiere pasar a entero
// sumarle antes 0.5
// Es demasiado preciso, ahora vendría la optimización para evitar
// las lentas sqrt(), para lo que se necesita no se requiere
// tanta precisión
//
// Falta el otro caso, de pendiente -1. Habría que poner una condición
// nada más entrar en la función: if (y2 < y1) {…} y hacer lo mismo
// pero con las pendientes negativas.
// https://gist.github.com/cf6e1d65bc2e8c3df7d7
#include <iostream>
#include <cmath>
using namespace std;
float distPsegm(int x1, int y1, int x2, int y2, int xp, int yp);
int main()
{
cout << distPsegm(1, 1, 3, 3, 3, 2) << endl;
cout << distPsegm(1, 1, 3, 3, 2, 2) << endl;
cout << distPsegm(1, 1, 3, 3, 4, 4) << endl;
cout << distPsegm(1, 1, 3, 3, 0, 0) << endl;
cout << distPsegm(1, 1, 3, 3, 0, 1) << endl;
return 0;
}
float distPsegm(int x1, int y1, int x2, int y2, int xp, int yp)
{
int dy1 = y1 - yp;
int dy2 = y2 - yp;
if (xp < x1 + dy1) {
// return distA;
cout << "A: ";
float x = x1 - xp;
return sqrt(x * x + dy1 * dy1);
}
if (xp <= x2 + dy2) {
cout << "B: ";
// return distB;
int dy = y2-y1;
int dx = x2-x1;
return (dy*xp-dx*yp-x1*y2+x2*y1)/(float)sqrt(dx*dx+dy*dy);
}
cout << "C: ";
// return distC;
float x = xp - x2;
return sqrt(x * x + dy2 * dy2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment