Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The sequence you want to evaluate converges towards pi. This sequence arises when you consider Taylor development of <code>arctan</code> function at <code>x=1</code>, therefore <code>arctan(1)=pi/4</code>:</p> <p><img src="https://upload.wikimedia.org/math/2/e/a/2ea1eb3e9bf135479e1a9eeb0157f22c.png" alt="arctan"></p> <p>Unfortunately this expansion does not converge very fast (think that all odd monoms are equal to 1, so you are loosing their convergence power). There is better ways to assess decimals of pi.</p> <p>Anyway, as stated before, recursion should not be used to solve this kind of problem. In fact recursion should be only used in few cases. Eg.: When you can prove that a divide and conquer algorithm reduce the complexity of the task you want to perform. <strong>In your case it does not at all, so avoid it.</strong> You will just fill up - and maybe overflow - your <code>call stack</code> without necessity. As pointed out by others your problem can be solved with a classic loop.</p> <p>You may solve it like this:</p> <pre><code>#include &lt;iostream&gt; #include &lt;iomanip&gt; #include &lt;cmath&gt; int main(void) { double x0 = 0.0; double x1 = 0.0; double eps = 0.0001; double s = 1.0; int i = 0; int maxiter = 100000; do { // Save Previous Term in order to compare with the next: x0 = x1; // Compute Next Term: x1 += s*4.0/(2*static_cast&lt;double&gt;(i)+1); // Change Sign: s *= -1.0; // Increase Counter: i++; // Log: std::cout &lt;&lt; std::setw(6) &lt;&lt; i &lt;&lt; std::fixed &lt;&lt; "\t" &lt;&lt; x1 &lt;&lt; "\t" &lt;&lt; std::setw(10) &lt;&lt; (x1-x0) &lt;&lt; std::endl; // Loop until convergence criterion is met or max iteration is reached: } while((std::abs(x1-x0)&gt;eps)&amp;&amp;(i&lt;maxiter)); return 0; } </code></pre> <p>If you do not know how many steps it will take to converge you need a <code>loop</code> instead of a <code>for</code> statement. In your case, <code>loop</code> is not necessary since you can write down the difference between two consecutive terms and determine how many steps it requires to be small enough with respect to your epsilon criterion.</p> <p>Anyway, if you use a loop you have to make sure that:</p> <ul> <li>Loop will ever exit at some point (avoid endless loop) ;</li> <li>When exiting, the result is correct.</li> </ul> <p>This is the reason why I use two criteria in my loop condition. The second is not necessary since I can show that distance between two consecutive terms vanishes to <code>0</code> as <code>i</code> grows. But I might want the loop stops before I reached some iteration threshold.</p>
 

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