Skip to content

Instantly share code, notes, and snippets.

@TheRayTracer
Created April 30, 2014 10:38
Show Gist options
  • Save TheRayTracer/92187ee5229b88d6dfb9 to your computer and use it in GitHub Desktop.
Save TheRayTracer/92187ee5229b88d6dfb9 to your computer and use it in GitHub Desktop.
Computes epsilon - the smallest value such that, when added to 1, is still distinguishable from 1.
#include <iostream>
#include <limits>
#include <cassert>
namespace std { }
using namespace std;
/* Computes the smallest value such that, when added to 1, is still distinguishable from 1. */
template<typename T>
int epsilon(T& eps)
{
int pow = 0;
eps = 1;
while (eps + 1 != 1)
{
eps /= 2;
--pow;
}
eps *= 2;
return pow + 1;
}
int main()
{
float feps = 0.0f;
double deps = 0.0;
int feps_2pow = epsilon<float>(feps);
int deps_2pow = epsilon<double>(deps);
cout << "Epsilon for float: 2^" << feps_2pow << " (" << feps << ")" << endl;
cout << "Epsilon for double: 2^" << deps_2pow << " (" << deps << ")" << endl;
assert(numeric_limits<float>::epsilon() == feps);
assert(numeric_limits<double>::epsilon() == deps);
cin.get();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment