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.