Why do I get the same results every time I call the std :: nexttoward function

Why std::nexttowarddoes the following code return the same number every time the function is called ?

#include <cmath>
#include <iostream>
#include <limits>

int main()
{
    std::cout.precision(std::numeric_limits<double>::max_digits10);
    std::cout.setf(std::ios::fixed);

    auto foo = 0.00000000000011134;
    std::cout << foo << std::endl;

    for (int i = 0; i < 100; ++i)
    {
        foo = std::nexttoward(foo, 1.0);
        std::cout << foo << std::endl;
    }
}

http://coliru.stacked-crooked.com/a/551b6e2b867b2f3b

None of the flags mentioned here (FE_OVERFLOW, FE_UNDERFLOW and FE_INEXACT) are set.

+4
source share
1 answer

This is due to the fact that the floating point format, as a rule, is focused on preserving a certain number of significant digits.

std::cout.setf(std::ios::fixed);

std::ios::fixed "" ( ). , . , - precision().

std::ios::fixed ( precision()) , ( gcc 7.2.1, Coliru):

1.1134e-13
1.1134000000000001e-13
1.1134000000000002e-13
1.1134000000000003e-13
1.1134000000000005e-13
1.1134000000000006e-13
1.1134000000000007e-13
1.1134000000000008e-13
1.113400000000001e-13
1.1134000000000011e-13
1.1134000000000012e-13

... ..

( e-13) , std::ios::fixed .

+4
source

Source: https://habr.com/ru/post/1686607/


All Articles