cheap replacement for sqrt
-
- Posts: 71
- Joined: Sat Aug 14, 2004 3:42 pm
cheap replacement for sqrt
I am working at one very interesting thing which requires many square rooting, which is too slow. Is there a cheap replacement for sqrt from math.h ? Accuracy is NOT priority at all.
Use the Source!
-
- Posts: 39
- Joined: Sat Oct 30, 2004 4:35 pm
- Location: Boston, MA
- Contact:
if the range of numbers you need the square roots of is relatively small, you could just precalculate the square roots of the numbers at some interval and put them in a look up table and use linear interpolation to estimate the actual square root
untested code, but it should work.. not perfectly accurate, but you said you don't mind
Code: Select all
// to initialize:
int maxsqrt = 1024;
float sqrts[maxsqrt];
for (int i=0; i<maxsqrt; i++)
sqrts[i] = sqrt(i);
// to use:
float mysqrt(float x)
{
if(x>maxsqrt) // if we haven't precalculated it, do it the slow way:
return sqrt(x);
else
{
int roundedx = int(x); // rounds down to next lowest integer
return sqrts[roundedx] + (x-roundedx)*(sqrts[roundedx+1]-sqrts[roundedx]);
}
}
-
- Posts: 39
- Joined: Sat Oct 30, 2004 4:35 pm
- Location: Boston, MA
- Contact:
here, pick your favorite: http://www.azillionmonkeys.com/qed/sqroot.html