samedi 14 août 2021

Why combining floating point representation with precision is not working?

WHy is below code not giving proper output till requested precision? Please note that since i am using std::fixed so i am expecting precision to be representing digits after decimal points. Hope thats correct?

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

int main()
{
    double d3 = 50388143.0682372156805328369140625;
    std::cout << "d3 = " << d3 << std::endl; 
    std::cout << std::setprecision(17) << std::fixed << "d3 = " << d3 << std::endl; 
    std::cout << std::setprecision(20) << std::fixed << "d3 = " << d3 << std::endl; 
}

Produces output as

d3 = 5.03881e+07
d3 = 50388143.06823721528053284   // See its different than original floating point
d3 = 50388143.06823721528053283691 // See its different than original floating point

Why isn't the output coming as

d3 = 5.03881e+07
d3 = 50388143.06823721568053283
d3 = 50388143.06823721568053283691

I was expecting the output digits to match with input digits till requested precision but its not the case. Why so?

Aucun commentaire:

Enregistrer un commentaire