Last active
August 30, 2017 19:28
-
-
Save rosemichaele/f2302e0306130ea41f7994f7782ebd0f to your computer and use it in GitHub Desktop.
I came across the fast inverse square root algorithm after reading about it on Quora, and I decided to take a stab at implementing it in Python 3.
This file contains 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
from struct import pack, unpack | |
def inv_sqrt(n: float) -> float: | |
n_half = n / 2 | |
n_hex = hex(unpack('>l', pack('>f', n))[0]) | |
magic_num = '0x5f3759df' | |
guess_int = int(magic_num, 16) - (int(n_hex, 16) >> 1) | |
guess_float = unpack('>f', pack('>l', guess_int))[0] | |
better_guess = guess_float*(1.5 - n_half*guess_float**2) | |
return better_guess |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment