java - Calculate distance between two coordinate -


coordinate 1 : 44.000, 61.001 coordinate 2 : 44.000, 61.001 

here coordinate same expecting return 0 distance. returning below distance using below mention calculating formula.

distance between 2 coordinates : 8.35023072909283e-8 (means 0.0000000835023072909283)  coordinate 1 : 110.000, 89.001 coordinate 2 : 110.000, 89.001 

here coordinate same expecting return zero distance. returning below distance using below mention calculating formula.

distance between 2 coordinates : 1.5033016609322658e-7 (means 0.00000015033016609322658) 

for calculating distance have used below code :

math.sqrt(math.pow(coordinate2.getx() - coordinate1.getx(), 2) + math.pow(coordinate2.gety() - coordinate1.gety(), 2)) 

why above formula return 1.5033016609322658e-7 type of distance instead of zero?

note : coordinates values double.

it looks you're rounding values of coordinates 3 decimal places while displaying them. actual stored coordinates not same, due tiny accumulated floating point imprecision in whatever math you're using calculate them. since you're not rounding distance when displaying that, can see difference.

p.s. tidiness of code, should wrap distance calcutation method on coordinate class. , math.hypot useful too:

public double distance(coordinate c) {     return math.hypot(x - c.x, y - c.y); } 

Comments