Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading