Skip to content

Instantly share code, notes, and snippets.

@dschwen
Created April 13, 2016 23:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dschwen/44d5a6b839ade014e38da973b8d3d313 to your computer and use it in GitHub Desktop.
Save dschwen/44d5a6b839ade014e38da973b8d3d313 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <cstdlib>
#include <cmath>
typedef double Real;
int main()
{
unsigned int nans = 0;
Real in;
Real out;
for (unsigned n = 0; n < 10000000; ++n)
{
const unsigned int num_bytes = sizeof(Real);
for (unsigned int i = 0; i < num_bytes; ++i)
reinterpret_cast<unsigned char *>(&in)[i] = std::rand() & 255;
if (std::isnan(in))
{
nans++;
continue;
}
std::stringstream si;
si << std::scientific
<< std::setprecision(std::numeric_limits<Real>::digits10 + 1)
<< in;
std::stringstream so(si.str());
so >> out;
if (out != in)
{
std::cout << "Lost precision!" << in << " - " << out << " = " << (in-out) << '\n';
return 1;
}
}
std::cout << "Precision fully retained! (" << nans << " nans)\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment