Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing a long double or just a double for calculating pi?
    text
    copied!<p>I'm calculating pi using a long winded formula. I'm trying to get more familiar with floating point numbers etc. I have a working program that uses doubles. The problem with my code is:</p> <ol> <li>If I use a double, pi is only accurate to the 7th decimal place. I can't get it to be any more accurate.</li> <li>If I use a long double, pi is accurate up to the 9th decimal place however the code takes much longer to run. If I check for precision for less than 0.00000001 using a long double, pi returns a value of 9.4246775. I assume that this is due to the long double. </li> </ol> <p>My question is what is the most accurate variable type? How could I change my code to improve the precision of pi?</p> <p>Here is my code:</p> <pre><code>#include &lt;iomanip&gt; #include &lt;cstdlib&gt; #include &lt;iostream&gt; #include &lt;cmath&gt; using namespace std; int main() { double arctan; double pi; double precision; double previous=0; int y=3; int loopcount=0; cout&lt;&lt;"Start\n"; arctan=1-(pow(1,y)/y); do { y=y+2; arctan=arctan+(pow(1,y)/y); y=y+2; arctan=arctan-(pow(1,y)/y); pi=4*(arctan); // cout&lt;&lt;"Pi is: "; // cout&lt;&lt;setprecision(12)&lt;&lt;pi&lt;&lt;endl; precision=(pi*(pow(10,10)/10)); loopcount++; if(precision-previous&lt;0.000000001) break; previous=precision; } while(true); cout&lt;&lt;"Pi is:"&lt;&lt;endl; cout&lt;&lt;setprecision(11)&lt;&lt;pi&lt;&lt;endl; cout&lt;&lt;"Times looped:"&lt;&lt;endl; cout&lt;&lt;loopcount&lt;&lt;endl; return 0; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload