how to use more precision in c++

4.7k Views Asked by At

Hi i have built an algorithm to calculate pi but i use long float for it so i just get 3.14159 as a result, i need more precision. How? here is the code:

    #include <iostream>
#include <math.h>
using namespace std;

int main ()
{
  long double a, l, p, pi, r;
  long long int n, m;
  r = 100000;
  a = r * sqrt (3) / 2 ;
  n = 100000;
  m = 6;
  while (n > m)
  {
    a = sqrt (r / 2 * (r + a));
  m = m * 2 ;
  }
  l = sqrt (4 * (pow (r, 2) - pow (a, 2)));
  p = m * l;
  pi = p / (2 * r) ;
  cout << pi << endl;
  cout << "number of corners used: " << m << endl;
  return 0;
}

By the way there is a 24 core (12 dual core nodes) supercomputer at my high school, just in case

3

There are 3 best solutions below

6
On BEST ANSWER

There's more precision in that number than you're displaying. You just have to ask for it:

cout << std::setprecision(40) << pi << endl;

That gives me 3.141592653543740176758092275122180581093 when run on Codepad.

As double should have way more than enough precision for basic calculations. If you need to compute millions of places, there isn't a standard floating point representation big enough to handle that.

2
On

If you really want more precision (not just display more decimal places), you could consider using the GMP (Gnu Multi-precision) Library. You can specify the number of bytes to use for your doubles (8 bytes, 16 bytes, 32 bytes, 64 bytes, 128 bytes, ... ). The library is usually used for cryto algorithms (that need really large integers).

https://gmplib.org/

You'll probably want to look at this similar thread: C++ calculating more precise than double or long double

4
On
cout.precision(400);
  cout << pi << endl;