fast inverse square root 1sqrtx using the quake iii algorithm reference https en wikipedia orgwikifastinversesquareroot accuracy https en wikipedia orgwikifastinversesquarerootaccuracy compute the fast inverse square root of a floatingpoint number using the famous quake iii algorithm param float number input number for which to calculate the inverse square root return float the fast inverse square root of the input number example fastinversesqrt10 0 3156857923527257 fastinversesqrt4 0 49915357479239103 fastinversesqrt4 1 0 4932849504615651 fastinversesqrt0 traceback most recent call last valueerror input must be a positive number fastinversesqrt1 traceback most recent call last valueerror input must be a positive number from math import isclose sqrt allisclosefastinversesqrti 1 sqrti reltol0 00132 for i in range50 60 true https en wikipedia orgwikifastinversesquarerootaccuracy compute the fast inverse square root of a floating point number using the famous quake iii algorithm param float number input number for which to calculate the inverse square root return float the fast inverse square root of the input number example fast_inverse_sqrt 10 0 3156857923527257 fast_inverse_sqrt 4 0 49915357479239103 fast_inverse_sqrt 4 1 0 4932849504615651 fast_inverse_sqrt 0 traceback most recent call last valueerror input must be a positive number fast_inverse_sqrt 1 traceback most recent call last valueerror input must be a positive number from math import isclose sqrt all isclose fast_inverse_sqrt i 1 sqrt i rel_tol 0 00132 for i in range 50 60 true https en wikipedia org wiki fast_inverse_square_root accuracy
import struct


def fast_inverse_sqrt(number: float) -> float:
    
    if number <= 0:
        raise ValueError("Input must be a positive number.")
    i = struct.unpack(">i", struct.pack(">f", number))[0]
    i = 0x5F3759DF - (i >> 1)
    y = struct.unpack(">f", struct.pack(">i", i))[0]
    return y * (1.5 - 0.5 * number * y * y)


if __name__ == "__main__":
    from doctest import testmod

    testmod()
    
    from math import sqrt

    for i in range(5, 101, 5):
        print(f"{i:>3}: {(1 / sqrt(i)) - fast_inverse_sqrt(i):.5f}")