2016-11-20 263 views
-7

我有2個座標(A1和A2),通過直線連接(我的路徑)。如何計算給定座標(B1或B2)與直線的最短距離?如何計算距離路徑的最短距離?

A1 and A2 connected by straight line

+2

這是數學問題不是Java? –

+0

諮詢谷歌或一本好的數學書籍 – UnholySheep

+0

我對java相當新(並且數學不好)。不知道我應該使用哪個功能。 –

回答

0
  1. 數學

    wikipedia 的線和點之間的最短距離所解釋的,可以被計算爲 如下:

如果線通過兩個點P1 =(X1,Y1)和P2 =(X2,Y2),則(X0,Y0)的距離線的距離是: Blockquote

  • 爪哇implimentaion

    class Point { 
        double x,y; 
    
        Point(double pX, double pY){ 
        this.x= pX; 
        this.y= pY; 
        } 
    
        public double distance(Point A1, Point A2){ 
        double numerator = Math.abs((A2.y - A1.y)*this.x + (A2.x - A1.x)*this.y + A2.x*A1.y - A2.y*A1.x); 
        double denominator = Math.sqrt(Math.pow(A2.y - A1.y,2) + Math.pow(A2.x - A1.x,2)); 
    
        return numerator/denominator;  
        } 
    
    } 
    
  • 爲了計算由Points A1A2定義Point B和線之間的距離,可以使用方法distance這樣的:

    public static void main (String[] args) throws java.lang.Exception 
    { 
        Point A1 = new Point(0,3); 
        Point A2 = new Point(2,0); 
        Point B = new Point(0,0); 
    
        System.out.println(
         B.distance(A1,A2) 
        ); 
    } 
    

    而且here是代碼並在ideone運行。

    但懇求去降壓的基本知識,選擇了一些很好的和有趣的編碼書或嘖嘖,並給它一去,快樂編碼:)