Created
August 30, 2021 05:52
-
-
Save djinn/e1e2175d25bc34ef406999d0ffffe8f9 to your computer and use it in GitHub Desktop.
The tiny code to show some of the floating point errors.
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 <iostream> | |
#include <string> | |
#include <cinttypes> // for uint32_t | |
#include <cfenv> | |
#include <cmath> | |
std::string float_to_binary(float f) { | |
union {float f; uint32_t i;} u; | |
std::string str; | |
u.f = f; | |
for (int i = 0; i < 32; i++) { | |
if (u.i % 2) str.push_back('1'); | |
else str.push_back('0'); | |
u.i >>= 1; | |
} | |
return str; | |
} | |
void print_this(std::string s, float f) { | |
std::cout << s << " = " << float_to_binary(f) << std::endl; | |
} | |
void very_many_errors() { | |
float a; | |
// double a; // precision errors will be fixed with change to double; | |
int i; | |
a = 0.1; | |
print_this("0.1", a); | |
a = 0.0; | |
print_this("0.0", a); | |
std::feclearexcept(FE_ALL_EXCEPT); | |
a += 0.1; | |
print_this("0.1", a); | |
if(std::fetestexcept(FE_INEXACT)) | |
std::cout << "FE_INEXACT" << std::endl; | |
a -= 0.1; | |
print_this("0.0", a); | |
if(std::fetestexcept(FE_INEXACT)) | |
std::cout << "FE_INEXACT" << std::endl; | |
if (a == 0.0) { | |
// The system to come to this part of the decision | |
std::cout << "If 0.0" << std::endl; | |
} else { | |
std::cout << "Hang on why here" << std::endl; | |
} | |
} | |
// Floating point roundoff error. This should not terminate but there is rounding error | |
int should_not_terminate() { | |
double a = 0.2; | |
int i; | |
a += 0.1; | |
a -= 0.3; | |
for (i = 0; a < 1.0; i++) | |
a += a; | |
std::cout << "i=" << i << " ; " << "a=" << a << std::endl; | |
return 0; | |
} | |
int main() { | |
should_not_terminate(); | |
very_many_errors(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment