Note that there are some explanatory texts on larger screens.

plurals
  1. POCalculate multiplicative inverse of positive real number
    text
    copied!<p>I wanted to calculate the multiplicative inverse of a positive real number without using division. After reading through various pages on Newton Raphson method, i implemented the following code for calculating the inverse:</p> <pre><code>#define PRECISION 0.1e-5 double inverse(double num) { double ans = num; while (ans * num &gt; 1 + PRECISION || ans * num &lt; 1 - PRECISION) { ans = ans * (2 - num * ans); } return ans; } </code></pre> <p>Now, the problem is, I actually do not get the inverse value. The loop goes on infinitely.</p> <p>So, <strong>1st</strong> thing I noticed was: The value of <code>ans</code> become negative, I added a statement <br><code>if (ans &lt; 0) ans *= -1;</code> <br>so that <code>ans</code> remains positive always.</p> <p><strong>2nd</strong> point to be noticed: If my initialization for <code>ans = 0.5</code> then I get the correct answer for a few values of <code>num</code> = <code>(1, 2, 3, 5)</code>.</p> <p>So, my assumption is, that the implementation isn't working because of inappropriate initialization of the variable <code>ans</code>.</p> <p>So, finally my questions: <br><strong>1</strong>.Can this method actually be used to calculate inverse of all positive real numbers? <br><strong>2</strong>.If yes, then are there any conditions required for the initial value assumed when using Newton Raphson method? <br><strong>3</strong>.Is there any other better method to calculate reciprocal without using division?</p> <h2><strong>EDIT:</strong></h2> <p>Thanks for the answer. So, as mentioned in the answer, I changed my initial value of <code>ans</code> to <code>PRECISION</code> and it works! Also, now as the initial value is good for particular max limit on <code>num</code>, <code>ans</code> never becomes negative, so no need for the negative checking condition that I had added initially.</p> <p>So, this is the working code (atleast works for the input I have given.)</p> <pre><code>double inverse(double num) { // Added to make it valid for all inputs. // For a too large number under the precision constraint, the answer is 0. if (num &gt; 999999) return 0; double ans = PRECISION; while (ans * num &gt; 1 + PRECISION || ans * num &lt; 1 - PRECISION) { ans = ans * (2 - num * ans); } return ans; } </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