fork(1) download
  1. #include <cmath>
  2. #include <iostream>
  3. #include <iomanip>
  4. #include <limits>
  5.  
  6. using namespace std;
  7.  
  8. void f(const uint64_t n) {
  9. const auto d = static_cast<double>(n);
  10. const long double ld = n;
  11.  
  12. cout << "Original: " << n << endl << setprecision(50);
  13.  
  14. if(ld == d) {
  15. cout << "Lower bound: " << d << "\nUpper bound: " << d << "\nPrecision loss: " << 0.0 << "\n\n";
  16. } else if(ld < d) {
  17. const double f = nextafter(d, -numeric_limits<double>::infinity());
  18.  
  19. cout << "Lower bound: " << f << "\nUpper bound: " << d << "\nPrecision loss: " << abs(d - f) << "\n\n";
  20. } else {
  21. const double f = nextafter(d, numeric_limits<double>::infinity());
  22.  
  23. cout << "Lower bound: " << d << "\nUpper bound: " << f << "\nPrecision loss: " << abs(d - f) << "\n\n";
  24.  
  25. }
  26. }
  27.  
  28. int main() {
  29. f(numeric_limits<uint64_t>::max()); // Rounds up
  30. f(numeric_limits<uint64_t>::max() - 2046); // Rounds down
  31. }
Success #stdin #stdout 0s 4424KB
stdin
Standard input is empty
stdout
Original:          18446744073709551615
Lower bound:       18446744073709549568
Upper bound:       18446744073709551616
Precision loss:    2048

Original:          18446744073709549569
Lower bound:       18446744073709549568
Upper bound:       18446744073709551616
Precision loss:    2048