java - Distance of point from a line not working -


i calculating distance of point line. getting wrong distance. following piece of code gettting distance line.

float px,py,something,u; px=x2-x1; py=y2-y1;  = px*px + py*py;  u =  ((x - x1) * px + (y - y1) * py) /(something);   if( u > 1) {     u = 1;     // mindist=0; } else if (u < 0) {     u = 0;     //mindist=0; }   float xx = x1 + u * px; float yy = y1 + u * py;  float dx = xx - x; float dy = yy - y;  float dist= (float)math.sqrt((double)dx*dx +(double) dy*dy); 

dist giving wrong answer.

from: http://en.wikipedia.org/wiki/distance_from_a_point_to_a_line#vector_formulation

distance(x=a+tn, p) = ||(a-p)-((a-p).n)n|| 

where:

a = (x1, y1)              //first point on line n = |(x2-x1, y2-y1)|      //normalised direction vector p = (x, y)                //query point 

so, not going all, make functions , give meaningful names follow formular:

float[] = new float[]{x1, y1}; float[] n = new float[]{x2-x1, y2-y1}; normalize(n); float[] p = new float[]{x, y};  float[] aminusp = subtract(a, p); float aminuspdotn = dot(aminusp, n);  // vec2a.vec2b float dot(float[] vec2a, float[] vec2b) {    return vec2a[0]*vec2b[0] + vec2a[1]*vec2b[1]; }  // ||vec2|| float len(float[] vec2) {    return (float)math.sqrt(dot(vec2, vec2)); }  // vec2/||vec2|| void normalize(float[] vec2) {   float length = len(vec2);   vec2[0] /= length;   vec2[1] /= length; }  // vec2a - vec2b float[] subtract(float[] vec2a, float[] vec2b) {   return new float[]{vec2a[0]-vec2b[0],vec2a[1]-vec2b[1]}; } 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -