Thursday, February 21, 2013

Estimate Approximate Distance between two Points


In computer science, it takes much more calculation time to multiply two values or find the square root of a value than to add two values or use the right shift operator to divide an integer.Thus, if large amounts of functions for computing distance between two points on the plane  occur in the program, and the precision is not highly stressed, an algorithm for efficient computation of approximate distance can significantly raise the performance.

The Java code below is about a method for efficient calculation of distance between two points. The error between the real distance and approximate distance is generally less than 1.5%, and the maximum error is around 3 percent.


public class DistanceUtils {

 public static long FastDistance(long x1, long y1, long x2, long y2) {  
  long width = x1 > x2 ? x1 - x2 : x2 - x1;
  long height = y1 > y2 ? y1 - y2 : y2 - y1;
  long m, M;
  if (width < height){
     m = width;  M = height;
  }
  else{
     m = height; M = width;
  }


  if (m > M >> 1) {
   if (m > (M >> 1) + (M >> 2))
    return M + (m >> 2) + (m >> 3);
   else
    return M + (m >> 2) + (m >> 5);
  } else {
   if (m > M >> 2)
    return M + (m >> 3) + (m >> 4);
   else
    return M + (m >> 4);
  }
 }

}

1 comment:

  1. The design of the algorithm above is quite simple. Just use the Pythagoras rule to calculate the hypotenuse's length of right-angled triangles with an excel file, and then observe the four formulas.

    ReplyDelete