4 Oct 2014

Algo #113: Inverse of a number (without division)

Problem Statement:
                Calculate Inverse of number without using '/ '  operator.

Solution:
       There could be multiple techniques for solving this problem but in this post i will solve this problem using Newton Raphson's Method. Refer to my earlier post on Newton Raphson for Square Roots.


Lets code up our logic.

public static void main(String[] args) {
  inverse(0.2f);
  inverse(0.3f);
  inverse(3.3f);
 }

 private static float inverse(float num) {
  float x1= num,x2=0,temp=num,e=0.001f;
  do 
  {
   x1 = temp;
   x2 = x1 * (2 - num*x1);
   temp=x2;
  }while(Math.abs(x2-x1)> e);
  
  System.out.println(num + " ----> " + x2);
  return x2;
 }

PS: The choice of the initial value may or may not converge the function and thus may not give correct result which is drawback of Newton Raphson's method

References:
1. http://www.sosmath.com/calculus/diff/der07/der07.html
2. https://www.math.ubc.ca/~anstee/math104/104newtonmethod.pdf
3. http://www.codecogs.com/eqnedit.php
4. Wiki

1 comment: