Advertisement
Guest User

Fraction

a guest
Oct 1st, 2014
338
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.65 KB | None | 0 0
  1. public class fraction {
  2.  
  3.     private final double limit = 1.0E-6;
  4.        
  5.     //Input a decimal number and get the fraction
  6.     public String getFraction(double x) {
  7.      
  8.         double h1 = 1, h2 = 0, k1 = 0, k2 = 1;
  9.         double y = x;
  10.        
  11.         do {
  12.        
  13.             double a = Math.floor(y);
  14.             double aux = h1;
  15.             h1 = a*h1+h2;
  16.             h2 = aux;
  17.             aux = k1;
  18.             k1 = a*k1+k2;
  19.             k2 = aux;
  20.             y = 1/(y-a);
  21.            
  22.         } while (Math.abs(x-h1/k1) > x*limit );
  23.        
  24.         return ((int) h1) + "/" + ((int) k1);  
  25.     }
  26.  
  27.     //some other methods...
  28.    
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement