Skip to content

Figuring out the formula for two objects in 3d space

An answer to this question on Stack Overflow.

Question

I am trying to figure out the formula to get the distance between two objects in 3d space. So far, the answers are wrong when I run the program:

float Distance3D(const float & object1X , 
             const float & object1Y ,
             const float & object1Z , 
			 const float & object2X , 
             const float & object2Y ,
             const float & object2Z )
{
    float x = pow ((object2X - object1X),2);// for x
    float y = pow ((object2Y - object1Y),2);// for y
    float z = pow ((object2Z - object1Z),2);// for z
    float objectDistance = 0.0f;
    objectDistance = sqrt(object2X*object1X + object2Y*object1Y + object2Z*object1Z);
    cout << objectDistance << endl;
    return objectDistance;
}

Answer

Distance in 3D space is usually found using the Pythagorean Theorem.

The formula for this is

d^2=(x0-x1)^2+(y0-y1)^2+(z0-z1)^2

where d is the distance between the points.

Using this formula, your code should look like

float Distance3D(const float & object1X , 
             const float & object1Y ,
             const float & object1Z , 
             const float & object2X , 
             const float & object2Y ,
             const float & object2Z )
{
    float delta_x = pow (object2X - object1X,2);// for x
    float delta_y = pow (object2Y - object1Y,2);// for y
    float delta_z = pow (object2Z - object1Z,2);// for z
    float objectDistance = 0.0f;
    objectDistance = sqrt(delta_x*delta_x + delta_y*delta_y + delta_z*delta_z);
    cout << objectDistance << endl;
    return objectDistance;
}

Interestingly, for high-dimensional data the usefulness of this metric declines and the Manhatten distance can become a preferable metric. A paper entitled "On the Surprising Behavior of Distance Metrics in High Dimensional Space" by Aggarwal (2001) has been wrote about this.