Bill the Lizard
Bill the Lizard

Reputation: 405725

What is the precision of long double in C++?

Does anyone know how to find out the precision of long double on a specific platform? I appear to be losing precision after 17 decimal digits, which is the same as when I just use double. I would expect to get more, since double is represented with 8 bytes on my platform, while long double is 12 bytes.

Before you ask, this is for Project Euler, so yes I do need more than 17 digits. :)

EDIT: Thanks for the quick replies. I just confirmed that I can only get 18 decimal digits by using long double on my system.

Upvotes: 30

Views: 47349

Answers (3)

Norman Bo Graham
Norman Bo Graham

Reputation: 1

Both C and C++ define precision, C++11 adds more details. C++11 added the limits header file in the standard. Some defines measure mantissa bits and some measure display bytes in base 10.

C Header file: float.h

LDBL_MANT_DIG // BITs in long double MANTissa   ie: 64
DBL_MANT_DIG  // bits in double                 ie: 53

C++ Header file limits (since c++11)

std::numeric_limits<double>::digits   /* bits same as DBL_MANT_DIG */
std::numeric_limits<long double>::digits /* bits same as LDBL_MANT_DIG */ 
std::numeric_limits<double>::digits10    /* BYTES displayed base 10 */ 
std::numeric_limits<long double>::digits10 /* bytes displayed base 10 */ 

numeric_limits has other details as well. floating point might be one of two standards, one uses an extra bit. Thats a detail you can ignore if you use the defined macros. Otherwise, if you calculate, based on bits, you might be trivially off by 1/8th.

Upvotes: 0

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 506857

You can find out with std::numeric_limits:

#include <iostream>     // std::cout
#include <limits>       // std::numeric_limits
int main(){
    std::cout << std::numeric_limits<long double>::digits10 << std::endl;
}

Upvotes: 41

user7116
user7116

Reputation: 64068

You can use <cfloat>. Specifically:

LDBL_DIG

Upvotes: 6

Related Questions