Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>So, the first step when doing a recursive problem is to write out your iterative step, and the conditional at which you will stop recursing.</p> <p>Let's look at a function declaration:</p> <pre><code>float recursion(float n) { ... } </code></pre> <p>It sounds like your last iteration will be when:</p> <pre><code>(4. / n) - (4. / (n+2)) &lt; 0.0001 </code></pre> <p>And at each step, it looks like you want to add that delta to the total:</p> <pre><code>total += (4. / n) - (4. / (n+2)) </code></pre> <p>So let's start:</p> <pre><code>float recursion(int n) { // Calculate the delta at each step... const float delta = (4./n - 4./(n+2)); // If the delta is less than our tolerance, then we __don't__ recurse. // Depending on the requirements of your algorithm, you might return 0 here, // or delta as I have. if (delta &lt; 0.0001) return delta; // Otherwise, we should recurse. return delta + recursion(n+4); } </code></pre> <p>We could also implement this very easily as a loop instead of recursion. It's often helpful to do that to see the iteration process more clearly.</p> <pre><code>float iterative() { int n = 1; float total = 0; while (true) { // Calculate the delta at each step... const float delta = (4./n - 4./(n+2)); // If the delta is less than our tolerance, then we are done! if (delta &lt; 0.0001) return total + delta; // Otherwise, update the total and keep iterating. total += delta; n += 4; } } </code></pre> <p>Some things to note:</p> <ul> <li>In C, you need to be careful about integer division versus floating point division. In your code, you're fine because <code>n</code> is a float. In my code, I've changed <code>n</code> to be an integer, so I'm using <code>4.</code> instead of <code>4</code>, because that will be interpreted by the compiler as a <code>double float</code> (also known as a <code>double</code>), instead of as an integer.</li> <li>I'm iterating / recursing each time by 4. If you can't see why, then look at how much math is being done at each iteration.</li> <li>We only pass the denominator (which you named <code>n</code>) to each recursive function. Naming your variables better can help make this more clear.</li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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