Last active
August 10, 2017 08:01
-
-
Save vietlq/783a369373e80c147c08583839fed23e to your computer and use it in GitHub Desktop.
Floats and Doubles for Dummies: Understanding Floating Points
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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