Albertus
Albertus

Reputation: 66

G++ floating point precision

I have these lines in a C++ program,

auto f = log (FLT_MAX / 4);
printf("%e", f);
cout << f;

The printf result is 8.733654e+1, but cout gives me 87.3365. I checked the 32-bit hex values, they're respectively 0x3f5f94e0 and 0x3f5f94d9, meaning, there seems to be enough precision to represent the value exactly.

Do you know why cout is truncating that floating point value?

Upvotes: 1

Views: 380

Answers (2)

ForceBru
ForceBru

Reputation: 44838

This has nothing to do with g++.

What you should do is this:

#include <limits>
#include <iomanip>

std::cout << std::setprecision(std::numeric_limits<double>::digits10+1) << f;

You can also use long double instead of double to get the maximum precision available.


Documentation

Upvotes: 1

DevSolar
DevSolar

Reputation: 70263

Do you know why cout is truncating that floating point value?

Because the default precision C++ streams are set to is 6.

You can change the precision with std::setprecision.

Upvotes: 1

Related Questions