Skip to content

Instantly share code, notes, and snippets.

@donno2048
Last active April 24, 2022 18:28
Show Gist options
  • Save donno2048/02f8ca2a31987e6e29dba2055cb98950 to your computer and use it in GitHub Desktop.
Save donno2048/02f8ca2a31987e6e29dba2055cb98950 to your computer and use it in GitHub Desktop.
Inverse square root and fast inverse square root
# Inverse square root and fast inverse square root
from ctypes import c_long, c_float, addressof, cast, POINTER
def fisr(number: float) -> float:
y = c_float(number)
i = c_long(0x5f3759df - (cast(addressof(y), POINTER(c_long)).contents.value >> 1))
y = cast(addressof(i), POINTER(c_float)).contents.value
return y * (3 - (number * y * y)) / 2
"""
float fisr(float number) {
float y = number;
long i = 0x5f3759df - (*(long*) &y >> 1);
y = *(float *) &i;
return y * (3.f - (number * y * y)) / 2.f;
}
"""
def isr(number: float) -> float:
return 1 / number ** .5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment