Are you familiar with
A^2 = B^2 + C^2?
I'd think something like:So you'd actually want to use
A^2 > B^2 + C^2
to find out if your two points were within 50 of each other.
if (sqrt(b*b + c*c) <= 50.0)
A^2 + B^2 = C^2[/URL].
I'd think something like:
would be more clear.Code:if (sqrt(b*b + c*c) <= 50.0)
This is probably one of the first times i see this formula being applied and used in real life, i always thought its just another pointless topic that the school forces you to learn.
However, wouldn't a sqrt function be rather expensive compared to an extra multiplication?
2012-01-30 13:13:53.915 SquareRootCost3[22875:f803] Beginning Test with squares.
2012-01-30 13:13:53.941 SquareRootCost3[22875:f803] Finished test with squares - found 369212
2012-01-30 13:13:53.941 SquareRootCost3[22875:f803] Beggining test with roots.
2012-01-30 13:13:53.954 SquareRootCost3[22875:f803] Finished test with roots - found 369212
srand(time(NULL));
int i = 0;
float a[500000], b[500000], c[500000];
for (i = 0; i < 500000; i++)
{
a[i] = rand();
b[i] = rand();
c[i] = rand();
}
long int squareans = 0;
long int rootans = 0;
NSLog(@"Beginning Test with squares.");
for (int i = 0; i < 500000; i++)
{
if (a[i]*a[i] < (b[i]*b[i] + c[i]*c[i]))
{
squareans++;
}
}
NSLog(@"Finished test with squares - found %ld", squareans);
NSLog(@"Beggining test with roots.");
for (int i = 0; i < 500000; i++)
{
if (a[i] < sqrtf(b[i]*b[i] + c[i]*c[i]))
{
rootans++;
}
}
NSLog(@"Finished test with roots - found %ld", rootans);
I made a quick app that tests which is faster, this is the output:
Code:2012-01-30 13:13:53.915 SquareRootCost3[22875:f803] Beginning Test with squares. 2012-01-30 13:13:53.941 SquareRootCost3[22875:f803] Finished test with squares - found 369212 2012-01-30 13:13:53.941 SquareRootCost3[22875:f803] Beggining test with roots. 2012-01-30 13:13:53.954 SquareRootCost3[22875:f803] Finished test with roots - found 369212
So the squares took 0.026 seconds while the roots took 0.013 seconds... it appears to take half as long to use squares. Odd.
sqrt() can probably take advantage of bitwise operators.