Message from C, C++ discussions

December 2019

— You may try adding -D_GNU_SOURCE to compiler invocation

— 

I want to implement a simple float comparison with epsilon in my project. But I also want to check with assertions that the values have comparable magnitudes with the given epsilon (so no one tries to compare one billion with something else using epsilon of 0.0001f). Is there a way to achieve that?

bool AreFloatsComparable(float a, float b, float epsilon)
{
return ???
}
bool AreEqualWithEpsilon(float a, float b, float epsilon)
{
Assert(AreFloatsComparable(a, b, epsilon), "error: ...");
return fabs(a - b) < epsilon;
}

— I have some code for that Ill send it when Im home

— 

[[nodiscard]] inline NO_ALIAS auto is_zero(const f32 v) noexcept->bool { return abs(v) < 1e-6f; }
[[nodiscard]] inline NO_ALIAS auto is_one(const f32 v) noexcept->bool { return is_zero(v - 1.f); }
[[nodiscard]] inline NO_ALIAS auto near_equal(const f32 a, const f32 b) noexcept->bool {
if (is_zero(a - b)) return true;
const s32 a2 = *reinterpret_cast<const s32*>(&a);
const s32 b2 = *reinterpret_cast<const s32*>(&a);
if (a2 < 0 != b2 < 0) return false;
return abs(a2 - b2) <= 0b0100;
}
[[nodiscard]] constexpr NO_ALIAS auto within_epsilon(const f32 a, const f32 b, const f32 epsilon) noexcept->bool {
const f32 num = a - b;
return -epsilon <= num && num <= epsilon;
}

Message permanent page

— Here just replace f32 with float and s32 with int, NO_ALIAS with __declspec(noalias) (only if you are on windows, otherwise remove it).

Message permanent page

— What abt this 🤯

— This is code for correctly comparing floating point numbers using epsilons :)

— Thanks, will have a look at this

— Your welcome, just write if you need more help :)

— Remember it is C++17 if you need it for C or an older std just write too

— I need it exactly for C++17 :)

— Alright :)