天天看点

已知两点坐标,求直线方程、距离其中一点距离为L的某点

         总觉得代码理应是无所不能的,尤其是在复杂的计算方面。而最近一个项目,要求计算坐标点,这尼玛遇到了要解方程组的情况,还是一元二次方程组。当时整个人都不好了,上网到处搜寻,也无法找到那种可以把表达式列出来,就给你解出来的方法。不过还好,网友的一些代码给了我不少的启发,于是摸出难得一用的纸笔,老老实实在草稿纸上演算,最终有了以下代码:

private void pointXY() {
		Point curPoint = new Point(20, 30);// 当前坐标
		Point nextPoint = new Point(35, 42);// 下个点坐标
		double distance = Math.sqrt(Math.pow(curPoint.x - nextPoint.x, 2)
				+ Math.pow(curPoint.y - nextPoint.y, 2));// 两点的坐标距离
		double lenthUnit = distance / 5;// 单位长度
		// 第一步:求得直线方程相关参数y=kx+b
		double k = (curPoint.y - nextPoint.y) * 1.0
				/ (curPoint.x - nextPoint.x);// 坐标直线斜率k
		double b = curPoint.y - k * curPoint.x;// 坐标直线b
		// 第二步:求得在直线y=kx+b上,距离当前坐标距离为L的某点
		// 一元二次方程Ax^2+Bx+C=0中,
		// 一元二次方程求根公式:
		// 两根x1,x2= [-B±√(B^2-4AC)]/2A
		// ①(y-y0)^2+(x-x0)^2=L^2;
		// ②y=kx+b;
		// 式中x,y即为根据以上lenthUnit单位长度(这里就是距离L)对应点的坐标
		// 由①②表达式得到:(k^2+1)x^2+2[(b-y0)k-x0]x+[(b-y0)^2+x0^2-L^2]=0
		double A = Math.pow(k, 2) + 1;// A=k^2+1;
		double B = 2 * ((b - curPoint.y) * k - curPoint.x);// B=2[(b-y0)k-x0];
		int m = 1;
		double L = m * lenthUnit;
		// C=(b-y0)^2+x0^2-L^2
		double C = Math.pow(b - curPoint.y, 2) + Math.pow(curPoint.x, 2)
				- Math.pow(L, 2);
		// 两根x1,x2= [-B±√(B^2-4AC)]/2A
		double x1 = (-B + Math.sqrt(Math.pow(B, 2) - 4 * A * C)) / (2 * A);
		double x2 = (-B - Math.sqrt(Math.pow(B, 2) - 4 * A * C)) / (2 * A);
		double x = 0;// 最后确定是在已知两点之间的某点
		if (x1 == x2) {
			x = x1;
		} else if (curPoint.x <= x1 && x1 <= nextPoint.x || nextPoint.x <= x1
				&& x1 <= curPoint.x) {
			x = x1;
		} else if (curPoint.x <= x2 && x2 <= nextPoint.x || nextPoint.x <= x2
				&& x2 <= curPoint.x) {
			x = x2;
		}
		double y = k * x + b;
		Point mPoint = new Point((int) x, (int) y);
}