Skip to content

Instantly share code, notes, and snippets.

@vietlq
Last active August 10, 2017 08:01
Show Gist options
  • Save vietlq/783a369373e80c147c08583839fed23e to your computer and use it in GitHub Desktop.
Save vietlq/783a369373e80c147c08583839fed23e to your computer and use it in GitHub Desktop.
Floats and Doubles for Dummies: Understanding Floating Points
#include <cmath>
#include <iostream>
template<typename FP>
bool nearEqual(FP v1, FP v2, FP absTol)
{
return std::abs(v1 - v2) <= absTol;
}
template<typename FP>
bool nearEqual(FP v1, FP v2, FP absTol, FP relTol)
{
if ((v1 == v2) || std::abs(v1 - v2) <= absTol)
{
return true;
}
FP relDiff = 2*std::abs(v1 - v2)/(std::abs(v1) + std::abs(v2));
return relDiff <= relTol;
}
int main()
{
std::cout << nearEqual(0.2, 0.199999, 1e-6) << std::endl;
std::cout << nearEqual(0.2, 0.199999, 1e-6, 1e-4) << std::endl;
std::cout << nearEqual(0.2, 0.1999999, 1e-7) << std::endl;
std::cout << nearEqual(0.2, 0.1999999, 1e-7, 1e-4) << std::endl;
const float v0 = 0.2;
const float v1 = 0.199999;
const float v2 = 0.1999999;
const float absTol1 = 1e-6;
const float absTol2 = 1e-7;
const float relTol = 1e-4;
std::cout << nearEqual(v0, v1, absTol1) << std::endl;
std::cout << nearEqual(v0, v1, absTol1, relTol) << std::endl;
std::cout << nearEqual(v0, v2, absTol2) << std::endl;
std::cout << nearEqual(v0, v2, absTol2, relTol) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment