Re: Converting decimal number to carpenter's fractions
- Posted by DerekParnell (admin) May 06, 2012
- 2773 views
A bit more generic version ...
include std/math.e constant mm_inch = 1/25.4, cm_inch = 1/2.54, m_ft = 1000 / 304.8 function carp( atom x, atom conv = 1, integer base = 64) integer numerator integer denominator integer units integer sign -- Apply any Unit-of-measure conversion x *= conv -- Remember original sign and ensure working is on absolute value. if x >= 0 then sign = 1 else sign = -1 x = -x end if -- Express original value in terms of how many 'base' fragments it is (rounded) x = floor(x * base + 0.5) -- Get numerator in range of 0 to base-1 numerator = remainder(x, base) -- Strip off the non-fraction part units = (x - numerator) / base denominator = base if numerator > 0 then -- First, normalize the fraction in terms of GCD x = gcd(numerator, denominator) numerator /= x denominator /= x -- Next, normalize the fraction until either top or botton is an odd number. while remainder(numerator,2) = 0 and remainder(denominator,2) = 0 do numerator /= 2 denominator /= 2 end while end if return {units, numerator, denominator, sign} end function ? carp(0) -- {0,0,64,1} ? carp(1) -- {1,0,64,1} ? carp(-0.625) -- {0,5,8,-1} ? carp(2.314) -- {2,5,16,1} ? carp(127/128) -- {1,0,64,1} ? carp(127/128,,128) -- {1,127,128,1} ? carp(1/128) -- {0,1,64,1} ? carp(257/256) -- {1,0,64,1} ? carp(38, mm_inch) --> {1,1,2,1} ie. 38mm -> 1+1/2 inch ? carp(38, mm_inch, 1000) --> {1,62,125,1} ie. 38mm -> 1+62/125 inch ? carp(1/3, 1, 9) --> {0,1,3,1} ? carp(2/3, 1, 9) --> {0,2,3,1} ? carp(5/27, 1, 9) --> {0,2,9,1}

