Skip to content

Instantly share code, notes, and snippets.

@petrsm
Created December 21, 2017 13:46
Show Gist options
  • Save petrsm/ee54e688bc6de367ae3b84f0db69bca3 to your computer and use it in GitHub Desktop.
Save petrsm/ee54e688bc6de367ae3b84f0db69bca3 to your computer and use it in GitHub Desktop.
Fast log2 approximation
static NX_FORCEINLINE float FastLog2_P2(float a)
{
// Based on code by Norbert Juffa
// r = log2(1 + m) for m in [sqrt(0.5) - 1, sqrt(2.0) - 1] range
const int e = (FloatAsUInt(a) - 0x3f3504f3) & 0xff800000;
const float m = UIntAsFloat(FloatAsUInt(a) - e) - 1.0f;
const float i = (float)e * 1.19209290e-7f;
float r = -6.8969686599880982e-1f;
r = r * m + 1.4839160720006022f;
r = r * m + -1.2646480695796084e-3f;
return r + i;
}
static NX_FORCEINLINE float FastLog2_P3(float a)
{
// Based on code by Norbert Juffa
// r = log2(1 + m) for m in [sqrt(0.5) - 1, sqrt(2.0) - 1] range
const int e = (FloatAsUInt(a) - 0x3f3504f3) & 0xff800000;
const float m = UIntAsFloat(FloatAsUInt(a) - e) - 1.0f;
const float i = (float)e * 1.19209290e-7f;
float r = 4.4759492291223656e-1f;
r = r * m + -7.6096527469413136e-1f;
r = r * m + 1.4456437789495665f;
r = r * m + 5.8326606506381397e-4f;
return r + i;
}
static NX_FORCEINLINE float FastLog2_P4(float a)
{
// Based on code by Norbert Juffa
// r = log2(1 + m) for m in [sqrt(0.5) - 1, sqrt(2.0) - 1] range
const int e = (FloatAsUInt(a) - 0x3f3504f3) & 0xff800000;
const float m = UIntAsFloat(FloatAsUInt(a) - e) - 1.0f;
const float i = (float)e * 1.19209290e-7f;
float r = -3.2646323399139144e-1f;
r = r * m + 5.1888522452341036e-1f;
r = r * m + -7.2591518470029981e-1f;
r = r * m + 1.4416386189833927f;
r = r * m + 4.7638297248616513e-5f;
return r + i;
}
static NX_FORCEINLINE float FastLog2_P5(float a)
{
// Based on code by Norbert Juffa
// r = log2(1 + m) for m in [sqrt(0.5) - 1, sqrt(2.0) - 1] range
const int e = (FloatAsUInt(a) - 0x3f3504f3) & 0xff800000;
const float m = UIntAsFloat(FloatAsUInt(a) - e) - 1.0f;
const float i = (float)e * 1.19209290e-7f;
float r = 2.5384347251568954e-1f;
r = r * m + -3.9703738348466398e-1f;
r = r * m + 4.8700114843625382e-1f;
r = r * m + -7.1992337841478827e-1f;
r = r * m + 1.4425493859924388f;
r = r * m + -9.2658550204675742e-6f;
return r + i;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment