Is it faster to use regular distance or squared distance?

1.1k Views Asked by At

Is it faster to use the square root in a vector length / distance operation and then comparing to some value or is it faster to square the value that is compared and then don't use the square root? So basically in pseudo code, is this:

sqrt(x * x + y * y) > a 

faster then this:

x * x + y * y > a * a 
1

There are 1 best solutions below

0
On BEST ANSWER

I am showing this code , to let you know that how big is the square root function

Even though , we use an inbuild function , it has to go through these process

As you can see now , sqrt is a result of a looped function which has multiplication, division and addition

So if you do x * x + y * y > a * a it will take only lesser time than the sqrt method, which i can confirm with this.

sqrt(int n)
{

    float temp, sqrt;

    // store the half of the given number e.g from 256 => 128
    sqrt = n / 2;
    temp = 0;

    // Iterate until sqrt is different of temp, that is updated on the loop
    while(sqrt != temp){
        // initially 0, is updated with the initial value of 128
        // (on second iteration = 65)
        // and so on
        temp = sqrt;

        // Then, replace values (256 / 128 + 128 ) / 2 = 65
        // (on second iteration 34.46923076923077)
        // and so on
        sqrt = ( n/temp + temp) / 2;
    }

    printf("The square root of '%d' is '%f'", n, sqrt);
}