Convert Decimal number into Fraction

前端 未结 6 1659
挽巷
挽巷 2021-01-15 00:50

I am trying to convert decimal number into its fraction. Decimal numbers will be having a maximum 4 digits after the decimal place. example:- 12.34 = 1234/100 12.3456 = 1234

6条回答
  •  执念已碎
    2021-01-15 00:57

    My solution is quite simple, "lazy", runs by iteration, nothing fancy.

    In most languages that have a decent Math library, you'll need nothing more than the algo itself.

    But in bc, you'll need to implement simple functions such as

    int() to return integer part of a number ,
    abs() to return absolute value ,
    float() to return floating part of a number ,
    round() to round to nearest integer.
    

    If nothing is found after (1/eps) iterations, the loop breaks with the last result.

    eps=10^-4 /*Tweak for more or less accuracy */
    
    define int(x) {
      auto s ;
      s = scale ;
      scale = 0 ;
      x /= 1 ;
      scale = s ;
      return x ;
    }
    define round(x) { return int(x+.5-(x<0)) ; }
    define abs(x) { if ( x < 0 ) x=-x ; return x ; }
    define float(x) { return abs(x-int(x)) ; }
    
    define void frac(x) {
        auto f, j, n, z ;
        f = float(x) ;    
        j = 1 / eps ;
        z = .5 ;
        if ( f != 0 ) {
            while ( ( n++ < j ) && ( abs( z - round(z) ) > eps ) ) z = n / f ;
            n -= 1 ;
            if ( x < 0 ) n = -n ;
            x = int(x)
            z = round(z) ;
            print n + x*z , "/" , z , " = "
            if ( x != 0 )  print x , " + " , n , "/" , z , " = "
        }
        print x+n/z , "\n" ;
    }
    

    With standard accuracy (eps=.0001), you can get this :

    frac(-.714285)
    -5/7 = -.71428571428571428571
    
    sqrt(2)
    1.414213562373
    frac(sqrt(2))
    19601/13860 = 1 + 5741/13860 = 1.414213564213
    
    6-7/pi
    3.77183080
    eps=.000001 ; frac(6-7/pi)
    1314434/348487 = 3 + 268973/348487 = 3.77183080
    

提交回复
热议问题