Why is abs(x)+abs(y) different from sqrt(x*x + y*y)

I was making a Physics Engine in C++ when I noticed that when I replace:

float absDistance = sqrt(vectorDistance.x * vectorDistance.x + vectorDistance.y * vectorDistance.y);

With:

float absDistance = abs(vectorDistance.x) + abs(vectorDistance.y)

Different things happen.

I’m using the library <cmath>

I looked at a lot of stack exchanges but I couldn’t find anyone saying they’re different. My question is why are they different and how.

Here’s my code just in case you needed it:

    for (int i = 0; i < balls.size(); i++)
    {
        balls[i].acceleration += gravity;

        Vec2 vectorDistance = balls[i].position - constraintPosition;
        float absDistance = sqrt(vectorDistance.x * vectorDistance.x + vectorDistance.y * vectorDistance.y);
        // float absDistance = abs(vectorDistance.x) + abs(vectorDistance.y)

        if (absDistance > constraintRadius - balls[i].radius)
        {
            balls[i].position = constraintPosition + (vectorDistance / absDistance) * (absDistance - balls[i].radius);
        }

        balls[i].update(dt);
        window.draw(balls[i].sprite);
    }

When I used abs() the collision would be in a diamond shapelike this

But if I use sqrt(x*x + y*y) I get a collision in a circle shape

>Solution :

Because the first is the Euclidean distance and the other is the Manhattan distance.

Leave a Reply