This is a proof-of-concept code that shows how to make C-like bitwise manipulations using only native luau features. Despite the name, it is actually slower and less precise than if you were to use 1/math.sqrt(). So don’t use it seriously.
--!strict
--!native
local evil = buffer.create(4)
local function Q_rsqrt(number:number) : number
local x2:number = number * 0.5
buffer.writef32(evil,0,number) -- evil floating point bit manipulation
buffer.writei32(evil,0,0x5f3759df - bit32.rshift(buffer.readi32(evil,0),1)) -- what the ####?
local y:number = buffer.readf32(evil,0)
y = y * ( 1.5 - ( x2 * y * y ) ) -- 1st iteration
--y = y * ( 1.5 - ( x2 * y * y ) ) -- 2nd iteration, this can be removed
return y
end
This also retains the original comments. I would like to hear what you think of it.