工作中需要判断点与矢量的位置关系,即点在矢量左侧或者右侧,找了看了一下理论,其实就是简单的高中知识,只不过都忘差不多了,不过不难,直接上代码(JAVA)。
package cn.xue.Algorithm;
public class pointAndLine01 {
/**
* 判断点与向量位置关系
*/
private static boolean pointAndLine(point pt1,point pt2,point pt) {
double temp=(pt1.y-pt2.y)*pt.x+(pt2.x-pt1.x)*pt.y+pt1.x*pt2.y-pt2.x*pt1.y;
if(temp>0) {
return true;
}else {
return false;
}
}
public static void main(String[] args) {
point pt2=new point(0,0);
point pt1=new point(20,20);
point pt=new point(21,20);
if(pointAndLine(pt1,pt2,pt)) {
System.out.println("点在矢量左边");
}else {
System.out.println("点在矢量右边");
}
}
}
其中有一个point类,如下:
package cn.xue.Algorithm;
public class point {
private double x;
private double y;
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public point(double x, double y) {
super();
this.x = x;
this.y = y;
}
}