| 1 |
#include <cmath> |
| 2 |
#include <cstdint> |
| 3 |
#include <cstdio> |
| 4 |
#include <cstdlib> |
| 5 |
#include <iostream> |
| 6 |
#include <limits> |
| 7 |
#include <string> |
| 8 |
|
| 9 |
union Double_t { |
| 10 |
Double_t(double val) : f(val) {} |
| 11 |
Double_t(int64_t val) : i(val) {} |
| 12 |
|
| 13 |
bool Negative() const { return (i >> 63) != 0; } |
| 14 |
int64_t RawMantissa() const { return i & ((int64_t(i) << 52) - 1); } |
| 15 |
int64_t RawExponent() const { return (i >> 52) & 0x7FF; } |
| 16 |
|
| 17 |
int64_t i; |
| 18 |
double f; |
| 19 |
|
| 20 |
struct { // Bitfields for exploration. Do not use in production code. |
| 21 |
uint64_t mantissa : 52; |
| 22 |
uint64_t exponent : 11; |
| 23 |
uint64_t sign : 1; |
| 24 |
} parts; |
| 25 |
}; |
| 26 |
|
| 27 |
int main(int argc, char* argv[]) |
| 28 |
{ |
| 29 |
// The last double value that still has precision as good as int. |
| 30 |
// The next double value is 2.0 bigger. |
| 31 |
Double_t num(0x1.fffffffffffffp52); |
| 32 |
|
| 33 |
// Comment out the line below, then you'll notice that it's impossible to |
| 34 |
// increment by 1.0 on the double value! |
| 35 |
// num.i++; |
| 36 |
|
| 37 |
std::printf( |
| 38 |
"Float value, int value, storage in hex, " |
| 39 |
"storage in dec, sign, exponent, mantissa\n"); |
| 40 |
std::printf("%1.8e, %ld, 0x%08lx, %ld, %d, %d, 0x%06lx\n", num.f, std::lrint(num.f), num.i, |
| 41 |
num.i, num.parts.sign, num.parts.exponent, num.parts.mantissa); |
| 42 |
|
| 43 |
double d1 = num.f; |
| 44 |
num.i += 1; |
| 45 |
double d2 = num.f; |
| 46 |
std::cout << "after increment by 1, d2 - d1 = " << d2 - d1 << std::endl; |
| 47 |
num.i -= 2; |
| 48 |
d2 = num.f; |
| 49 |
std::cout << "after decrement by 1, d2 - d1 = " << d2 - d1 << std::endl; |
| 50 |
|
| 51 |
// std::cout << std::lrint(num.f) << std::endl; |
| 52 |
// std::cout << std::numeric_limits<int32_t>::max() << std::endl; |
| 53 |
// std::cout << std::numeric_limits<int64_t>::max() << std::endl; |
| 54 |
} |