Skip to content

Instantly share code, notes, and snippets.

@aztennenbaum
Last active February 6, 2024 22:34
Show Gist options
  • Select an option

  • Save aztennenbaum/4faf0d068d4e8afaedfcf576f5262c00 to your computer and use it in GitHub Desktop.

Select an option

Save aztennenbaum/4faf0d068d4e8afaedfcf576f5262c00 to your computer and use it in GitHub Desktop.
fast inverse squareroot, generalized to arbitrary powers in the range [1,-1]
#include <stdio.h>
#include <stdint.h>
#include <float.h>
#include <math.h>
float q_pow(float x, float y)
{
union {
float f;
uint32_t i;
} conv = { .f = powf(FLT_MAX/2, -y) };
printf("magic_number: fnum=%f inum=0x%x\n",conv.f,conv.i);
/* It's cool how optimizing compilers are a thing, so we dont have
* hardcode some weird hex number like magic_num = 0x5f3759df
* I imagine that would be really confusing :-) */
uint32_t magic_num = conv.i;
conv.f = x;
conv.i = magic_num + conv.i*y;
return conv.f;
}
int main()
{
float number = 1<<16;
printf("q_pow(%f)=%f\n",number,q_pow(number,-3.0/16.0));
printf("powf(%f)=%f\n",number,powf(number,-3.0/16.0));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment