Skip to content

Instantly share code, notes, and snippets.

@Lokno
Last active July 21, 2021 16:10
Show Gist options
  • Select an option

  • Save Lokno/688158b7a11484b6c018ceeb676a952a to your computer and use it in GitHub Desktop.

Select an option

Save Lokno/688158b7a11484b6c018ceeb676a952a to your computer and use it in GitHub Desktop.
simple float / safe float (WIP)
// simple float / safe float (WIP)
//
// For when you want your math to be real with you
//
// drop-in replacement for a IEEE single-precision float that
// maintains a real-number
//
// Optionally define SFLOAT_ABORT_NONREAL fail on first occurance
// of a non-real number
//
// -INF => -3.40282346638528859812e+38
// INF => 3.40282346638528859812e+38
// NaN => 0.0
//
// TODO: Use templating to allow for float or double representation (and ONLY float or double types)
#pragma once
#include <cmath>
#include <cassert>
class sfloat
{
public:
sfloat():x(0.0f) {};
sfloat( const sfloat& rhs ) { x = rhs.x; };
sfloat& operator=(const float value) { x = value; check(); return *this; };
sfloat operator +(const float value) { sfloat t; t.x += value; t.check(); return t; };
sfloat operator -(const float value) { sfloat t; t.x -= value; t.check(); return t; };
sfloat operator *(const float value) { sfloat t; t.x *= value; t.check(); return t; };
operator float() const { return x; };
operator double() const { return static_cast<double>(x); };
private:
void check()
{
if( std::isnan(x) )
{
#ifdef SFLOAT_ABORT_NONREAL
assert(false);
#endif
x = 0.0f;
}
if( std::isinf(x) )
{
#ifdef SFLOAT_ABORT_NONREAL
assert(false);
#endif
if( x < 0.0f )
x = -std::numeric_limits<float>::max();
else
std::numeric_limits<float>::max();
}
}
float x;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment