Main Menu

Fast Inverse Square Root

Started by kevin, November 24, 2021, 07:03:06 AM

Previous topic - Next topic

kevin

Inverse Square Root

    This is port of sorts of the inverse square roots function found in Quake and is represent here for nothing more novelty purposes.    The reason for that is a Sqrt() function from runtime would most likely work out faster than trying to side step with bit manipulation.  Due to the cost of executing those extra operations on the Pb runtime.



PlayBASIC Code: [Select]
   constant threehalfs# = 1.5
global q_rsqrt_Bank = newbank(256)
global q_rsqrt_BankPtr = getbankptr( q_rsqrt_Bank)
wait 20
sync

for Number=0 to 100000

n#=number*1.01234
r1#=Q_rsqrt#( n# )
r2#= 1 / sqrt( n# )

#print r1#
#print r2#
e#=r2#-r1#

he#=maxval#(e#,he#)
le#=minval#(e#,le#)
next

print he#
print le#


sync
waitkey



Function Q_rsqrt#( number# )

x2# = number# * 0.5
y# = number#

//i = * ( long * ) &y; // evil floating point bit level hacking
// get the bitpattern of Copy Y#
pokefloat q_rsqrt_BankPtr, y#
i=peekint(q_rsqrt_BankPtr)

//i = 0x5f3759df - ( i >> 1 ); // what the f--k?
i = 0x5f3759df - ( i >> 1 )

// y = * ( float * ) &i;
pokeint q_rsqrt_BankPtr, i
y#=peekfloat(q_rsqrt_BankPtr)

//y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
y# = y# * ( threehalfs# - ( x2# * y# * y# ) )


EndFunction y#

/*

float Q_rsqrt( float number )
{
long i;
float x2, y;
const float threehalfs = 1.5F;

x2 = number * 0.5F;
y = number;
i = * ( long * ) &y; // evil floating point bit level hacking
i = 0x5f3759df - ( i >> 1 ); // what the f***?
y = * ( float * ) &i;
y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed

return y;
}

*/








       
   Fast inverse square root (from quake)