When using the IEEE 754 floating point representation ( doubletype in C ++), numbers that are very close to (representable) integers are rounded to their nearest integer and displayed accurately. It's true? Exactly how close should the number be to the nearest represented integer before rounding?Is this distance constant?For example, given that 1 can be represented exactly, which largest is doubleless than 1?
double
IEEE 754 (double ++), , () , .
, , . 0.99999999999999994 1, 0.99999999999999995 .
0.99999999999999994
1
0.99999999999999995
?
, - , . , , , , .
, 1?
std::nexttoward(1.0, 0.0). . 0.999999999999999889 Coliru.
std::nexttoward(1.0, 0.0)
0.999999999999999889
1.0 1.0 :
std::numeric_limits<double>::epsilon()
, 1.0 .
IEEE 1 0.99999999999999989, 0.99999999999999988897769753748434595763683319091796875.
, (, , ) . 1, , ( - , ) (, , ).
IEEE :
(Intel):
#include <cstdint> #include <iostream> #include <limits> int main() { double one = 1; std::uint64_t one_representation = *reinterpret_cast<std::uint64_t*>(&one); std::uint64_t lesser_representation = one_representation - 1; std::cout.precision(std::numeric_limits<double>::digits10 + 1); std::cout << std::hex; std::cout << *reinterpret_cast<double*>(&lesser_representation) << " [" << lesser_representation << "] < " << *reinterpret_cast<double*>(&one_representation) << " [" << one_representation << "]\n"; }
:
0.9999999999999999 [3fefffffffffffff] < 1 [3ff0000000000000]
, .
: http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
IEEE 754 ( ++) , , . ?
.
, int ?
When you perform a binary conversion, the floating-point number is rounded to the current precision (the printfdefault value for the family of functions is 6) using the current rounding mode.
printf