使用规则距离还是平方距离更快



在向量长度/距离运算中使用平方根,然后与某个值进行比较,速度更快吗?还是对所比较的值进行平方,然后不使用平方根更快?所以基本上在伪代码中,是这样的吗:

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

比这个更快:

x * x + y * y > a * a 

我展示这段代码,让您知道的平方根函数有多大

即使我们使用内置函数,它也必须经过这些过程

正如您现在所看到的,sqrt是具有乘法、除法和加法的循环函数的结果

所以如果你做x * x + y * y > a * a,它只需要比sqrt方法花费更少的时间,我可以用这个来确认。

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);
}

最新更新