https://en.wikipedia.org/wiki/Fast_inverse_square_root
So, why is Q_rsqrt() *slower* than 1/sqrt()?
1/sqrt() took 0.294771 s
Q_rsqrt() took 0.51579 s
--
↙↙↙ uǝlƃ
#include <stdio.h>
#include <math.h>
#include <time.h>
float Q_rsqrt( float number, int iterates) {
long i=0L;
float x2,y;
const float threehalfs = 1.5F;
x2 = number * 0.5F;
y = number;
i = * (long *) &y;
i = 0x5f3759df - (i>>1);
y = * (float *) &i;
for (int j=0;j<iterates;j++)
y = y * (threehalfs - (x2 * y * y));
return y;
}
int main() {
float result;
float x;
clock_t begin = clock();
for (x=1 ; x<2e6; x+=0.1) result = 1/sqrt(x);
clock_t end = clock();
printf("1/sqrt() took %lg s\n",(double)(end-begin)/CLOCKS_PER_SEC);
begin = clock();
for (x=1 ; x<2e6; x+=0.1) result = Q_rsqrt(x,1);
end = clock();
printf("Q_rsqrt() took %lg s\n",(double)(end-begin)/CLOCKS_PER_SEC);
//printf("(%f)^-½ = %f ≃ %f\n", x, 1/sqrt(x), Q_rsqrt(x,1));
return 0;
}
- .... . -..-. . -. -.. -..-. .. ... -..-. .... . .-. .
FRIAM Applied Complexity Group listserv
Zoom Fridays 9:30a-12p Mtn GMT-6 bit.ly/virtualfriam
un/subscribe http://redfish.com/mailman/listinfo/friam_redfish.com
archives: http://friam.471366.n2.nabble.com/
FRIAM-COMIC http://friam-comic.blogspot.com/