Mar 9, 2022

[C++] Largest value representable by a floating-point type smaller than 1

Reference:
https://stackoverflow.com/questions/71383519/largest-value-representable-by-a-floating-point-type-smaller-than-1

https://en.cppreference.com/w/cpp/numeric/math/nextafter


Question

Obtain the greatest value representable by the floating-point type float which is smaller than 1.

Ans

Portable solution(regardless of what floating-point format your C++ implementation uses. (Binary vs. decimal, or width of mantissa aka significand, or anything else.)), using std::nextafter
#include <iostream>
#include <iomanip>
#include <cmath>
#include <limits>

int main()
{
    double naft = std::nextafter(1.0, 0.0);
    std::cout << std::fixed << std::setprecision(20);
    std::cout << naft << '\n';
    double neps = 1.0 - std::numeric_limits<double>::epsilon();
    std::cout << neps << '\n';
    return 0;
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.