Last active
February 6, 2024 22:34
-
-
Save aztennenbaum/4faf0d068d4e8afaedfcf576f5262c00 to your computer and use it in GitHub Desktop.
fast inverse squareroot, generalized to arbitrary powers in the range [1,-1]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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