0

I'm simply trying to print the value of pi defined in math.h library. But I'm getting incorrect integers after the 15th decimal point.

#include <iostream>
#include <math.h>

using namespace std;

int main()
{
    cout.precision(20);  
    cout << "fixed:\n" << std::fixed;
    cout<<M_PI<<endl;
    // printf("%.*lf\n", 20, M_PI);
    return 0;
}

Output: 3.14159265358979311600

Expected output: 3.14159265358979323846 (which is defined in math.h library)

Question 1: If the answer to this question is related to floating-point arithmetic. Then why does math.h library defines the value of pi accurately up to 20 decimal places instead of 15?

Question 2: Is there a way of printing the accurate value of pi up to 20 decimal places? If yes, then please show.

Question 3: When I use the value of M_PI for other calculations which value is used? 3.14159265358979311600 or 3.14159265358979323846 ?

My hardware is Intel core i7 9th generation with 32GB RAM, Ubuntu 20.04 OS. I'm using the g++ compiler and C++17.

Thanks.

CuriousHash
  • 385
  • 1
  • 4
  • 17
  • 4
    Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Stephen Newell Jan 21 '22 at 05:02
  • 4
    To Q1, it's pretty common for floating-point constants defined in headers to use an excessive number of digits, that is more than the target's floating point types can actually represent. It doesn't hurt anything, and could help in case the header is someday ported to a platform that has higher-precision floating-point types. – Nate Eldredge Jan 21 '22 at 05:12
  • Though memory is only using 64 bit floating point values (depending on hardware) it is common to see 80 bit floating point registers. If the compiler can keep the floating point values in register rather than having to save it to memory it can use the more accurate values, but once saved to memory you will truncate to 64 bits and loose accuracy. So make sure you use optimizations and hope the ABI allows parameters to be passed to cout in the registers. – Martin York Jan 21 '22 at 06:59
  • Please note that the value you are seeing is the closest to pi of all the ones representable as a floating-point `double`: https://godbolt.org/z/sK418ErMx – Bob__ Jan 21 '22 at 10:23
  • @StephenNewell yea I get it now. Thanks – CuriousHash Jan 22 '22 at 11:37

0 Answers0