| 1 | #include <stdint.h>
|
|---|
| 2 | #include <stdio.h>
|
|---|
| 3 | #include <cmath>
|
|---|
| 4 | #include <iostream>
|
|---|
| 5 | #include <boost/multiprecision/cpp_bin_float.hpp>
|
|---|
| 6 |
|
|---|
| 7 | typedef boost::multiprecision::number<boost::multiprecision::cpp_bin_float<128, boost::multiprecision::backends::digit_base_2> > boost_quadfloat_t;
|
|---|
| 8 |
|
|---|
| 9 | double my_convert_to_double(const boost_quadfloat_t& x)
|
|---|
| 10 | {
|
|---|
| 11 | if (isnormal(x)) {
|
|---|
| 12 | if (x.backend().exponent() < -1023+1) {
|
|---|
| 13 | // subnormal or zero
|
|---|
| 14 | if (x.backend().exponent() < -1023 - 52) {
|
|---|
| 15 | return x.backend().sign() ? -0.0 : 0.0; // underflow
|
|---|
| 16 | }
|
|---|
| 17 | double adj = x.backend().sign() ? -DBL_MIN : DBL_MIN;
|
|---|
| 18 | boost_quadfloat_t tmp = x + adj;
|
|---|
| 19 | return tmp.convert_to<double>() - adj;
|
|---|
| 20 | }
|
|---|
| 21 | }
|
|---|
| 22 | return x.convert_to<double>();
|
|---|
| 23 | }
|
|---|
| 24 |
|
|---|
| 25 | int main(int , char** )
|
|---|
| 26 | {
|
|---|
| 27 | boost_quadfloat_t b = ldexp(boost_quadfloat_t(0x8000000000000bffull), -63 - 1023);
|
|---|
| 28 | double d0 = b.convert_to<double>();
|
|---|
| 29 | double d1 = std::nexttoward(d0, d0 < b ? DBL_MAX : -DBL_MAX);
|
|---|
| 30 |
|
|---|
| 31 | std::cout
|
|---|
| 32 | << std::setprecision(21)
|
|---|
| 33 | << b << " = b\n"
|
|---|
| 34 | << d0 << " = d0 = b.convert_to<double>()\n"
|
|---|
| 35 | << d1 << " = d1 = std::nexttoward(d0, ...)\n"
|
|---|
| 36 | << abs(d0 - b) << " = abs(d0 - b)\n"
|
|---|
| 37 | << abs(d1 - b) << " = abs(d1 - b)\n"
|
|---|
| 38 | << ((abs(d1 - b) < abs(d0 - b)) ? "d0 is not the closest representable double!!!\n" : "o.k.\n")
|
|---|
| 39 | ;
|
|---|
| 40 |
|
|---|
| 41 | d0 = my_convert_to_double(b);
|
|---|
| 42 | d1 = std::nexttoward(d0, d0 < b ? DBL_MAX : -DBL_MAX);
|
|---|
| 43 | std::cout
|
|---|
| 44 | << d0 << " = d0 = my_convert_to_double(b)\n"
|
|---|
| 45 | << d1 << " = d1 = std::nexttoward(d0, ...)\n"
|
|---|
| 46 | << abs(d0 - b) << " = abs(d0 - b)\n"
|
|---|
| 47 | << abs(d1 - b) << " = abs(d1 - b)\n"
|
|---|
| 48 | << ((abs(d1 - b) < abs(d0 - b)) ? "d0 is not the closest representable double!!!\n" : "o.k.\n")
|
|---|
| 49 | ;
|
|---|
| 50 |
|
|---|
| 51 | return 0;
|
|---|
| 52 | }
|
|---|