Float fractional accuracy

How many places of accuracy are there floatbetween 1.0fand 0.0fso that each value can be unambiguously represented?

For example, if the first fractional number floatcannot represent 0.13f, the answer would be that the float had only 1 precision place.

+4
source share
2 answers
std::numeric_limits<float>::digits10

From http://en.cppreference.com/w/cpp/types/numeric_limits/digits10

32- IEEE 754 24- (23 , , ), , (24 * std:: log10 (2) 7.22), , 7 32- : - 8.589973e9, 8.589974e9 . , 10 (24-1) * std:: log10 (2), 6.92. 6.

Edit2: , 7, 6 , std::numeric_limits<float>::digits10.

float orgF = 8.589973e9;
int i = orgF;
float f = i;
assert(f == orgF);

, roundtrip .

, 1.0 0.0, 7, , , 8.589973e9.

+7

, 6.

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;

int main() {
    int i = 10;  /* Number of distinct number after 1 place of decimal */
    int k = 1;   /* Number of decimal places */
    for(;/* ever */;)
    {
        float prev = 0.0f;
        for(int j = 1; j <= i; ++j)
        {
            stringstream ss;
            ss << "0.";  /* Prepare stream with 0. followed by k digit number with leading zeroes */
            ss << setfill('0') << setw(k) << j;
            float next; /* Read the number */
            ss >> next;
            if(prev == next) return 0;  /* If previous number and current number can not be distinguished */
            prev = next;
        }
        cout << "Works for " << k << " places" << endl;
        i *= 10; /* 10 times more tests to be conducted for 1 more decimal places */
        k++;     /* Try for more decimal places */
    }
    return 0;
}


1. Set precision to 1 place after decimal
2. Compare 0.0 with 0.1, 0.1 with 0.2 .... 0.8 with 0.9 and 0.9
   with 1.0, if any of these are equal (not distinguish), exit.
   Otherwise print Works for 1 place.
3. Set precision to 2 places after decimal
4. Compare 0.00 with 0.01, 0.01 with 0.02 .... 0.98 with 0.99 and 0.99
   with 1.00, if any of these are equal (not distinguish), exit. Otherwise
   print Works for 2 places.
5. Repeat similar steps for 3 and more digits unless you exit
+4

All Articles