What is the precision of long double in C++?
Asked Answered
E

2

30

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.

Erasure answered 24/1, 2009 at 16:8 Comment(2)
Is it possible that it's converting things to regular double at some point?Ogpu
Yes, that's definitely possible. I was up until 2AM checking my code for that last night, and I'm pretty sure it's long double all the way through, though.Erasure
S
39

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;
}
Savarin answered 24/1, 2009 at 16:13 Comment(7)
will that tell you the precision, or just the limits?Ogpu
it tell you the precision. i.e how many digits you can have in the double. min() and max() tell you the limitSavarin
More specifically it'll tell you how many you can round into a long double and not lose the digit.Octodecimo
yeah, while min() and max() will tell you the limit you can have even if you loose precision. max is 1.18973e+4932 here, while digits10 is 18.Savarin
Thanks for the reply. I'm getting the same results, 18 decimal digits. Now I'm wondering why 4 extra bytes of storage are needed to get one more decimal digit?Erasure
On x86 it tends to be the 80-bit extended format: 64bits of mantissa, 15bits of exponent, probably going to be around 18 round safe digits. Double is 53bit mantissa or 16 round safe digits.Octodecimo
What about max_digits10 vs digits10?Scarito
O
6

You can use <cfloat>. Specifically:

LDBL_DIG
Octodecimo answered 24/1, 2009 at 16:17 Comment(1)
Thanks for the link. It's LDBL_DIG that gives the decimal digits. LDBL_MANT_DIG gave me the binary digits.Erasure

© 2022 - 2024 — McMap. All rights reserved.