Comment detail

分数を小数に展開 (Nested Flatten)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
open System;;

let simplify (n,m) =
    let rec gcd a b =
        match a,b with
        | _,0 -> a
        | 0,_ -> b
        | a,b -> gcd b (a % b)
    and d = gcd n m in
    (n / d, m / d);;

let pow base index =
    int_of_float ( (float_of_int base) ** (float_of_int index) );;

let rec count2And5Factors n =
    let rec count base cnt = function
        | 0 -> cnt
        | m when not (m % base = 0) -> cnt
        | m -> count base (cnt+1) (m/base)
    in (count 2 0 n, count 5 0 n);;

let getRec (m,n) =
   let rec recurring index = function
       | 1 -> 0
       | num -> if ((pow 10 index) - 1) % num = 0
                 then ((pow 10 index) - 1) / num
                 else recurring (index+1) num
       in m * (recurring 1 n);;

let rec decimal_of_frac (m,n) =
    let (ixTwo, ixFiv) = count2And5Factors n in
         let rec r = max ixTwo ixFiv
         and divide (k,l) = int_of_float (float_of_int k / float_of_int l)
         and n' = n / (pow 2 ixTwo) / (pow 5 ixFiv)
         and m' = m * (pow 2 (r-ixTwo)) * (pow 5 (r-ixFiv))
         and finite_part = (divide (m',n'))
         and proper_m = m'-(finite_part * n')
         and recurring = getRec (simplify (proper_m,n'))
         and finite_dec = (float_of_int finite_part) * (10.0 ** -float_of_int r)
         in Printf.sprintf "%g{%d}" finite_dec recurring;;

Index

Feed

Other

Link

Pathtraq

loading...