Skip to content

Instantly share code, notes, and snippets.

@kayru
Last active October 26, 2017 14:53
Show Gist options
  • Save kayru/c6a21cbe8d3c3ab742342924dcc3f314 to your computer and use it in GitHub Desktop.
Save kayru/c6a21cbe8d3c3ab742342924dcc3f314 to your computer and use it in GitHub Desktop.
struct FloatBits
{
u32 mantissa : 23;
u32 exponent : 8;
u32 sign : 1;
};
template <typename ResultT, typename InputT>
inline ResultT bitCast(InputT v)
{
static_assert(sizeof(ResultT) == sizeof(InputT), "Size of source and destination must match.");
ResultT result;
memcpy(&result, &v, sizeof(v));
return result;
}
inline float computeEpsilon(float f, u32 epsilonMantissa /*e.g. 16*/)
{
FloatBits inputBits = bitCast<FloatBits>(f);
FloatBits epsilonBits1;
epsilonBits1.sign = 0;
epsilonBits1.exponent = inputBits.exponent;
epsilonBits1.mantissa = 0;
FloatBits epsilonBits2;
epsilonBits2.sign = 0;
epsilonBits2.exponent = inputBits.exponent;
epsilonBits2.mantissa = epsilonMantissa;
float e1 = bitCast<float>(epsilonBits1);
float e2 = bitCast<float>(epsilonBits2);
float result = e2 - e1;
return result;
}
inline float computeEpsilonPow2(float f, u32 exponentDiff /*e.g. 19*/)
{
FloatBits inputBits = bitCast<FloatBits>(f);
FloatBits epsilonBits;
epsilonBits.sign = 0;
epsilonBits.exponent = inputBits.exponent - std::min(inputBits.exponent, exponentDiff);
epsilonBits.mantissa = 0;
float result = bitCast<float>(epsilonBits);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment