Created
December 29, 2012 15:55
-
-
Save basilevs/4407717 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <limits> | |
| #include <assert.h> | |
| template<class T> | |
| long compensateOverflow(long near, T value) | |
| { | |
| using namespace std; | |
| static const long delta = long(numeric_limits<T>::max()) - numeric_limits<T>::min() + 1; | |
| assert(delta%2 == 0); | |
| assert(delta > 10); | |
| assert(value < delta); | |
| assert(value > -delta); | |
| long rv = near - near % delta + value ; | |
| if (rv < near - delta / 2 ) | |
| rv += delta; | |
| else if (rv > near + delta / 2) | |
| rv -= delta; | |
| assert(abs(rv - near) < delta / 2); | |
| return rv; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment