Skip to content

Instantly share code, notes, and snippets.

@Yonaba
Created June 29, 2011 14:56
Show Gist options
  • Save Yonaba/1054001 to your computer and use it in GitHub Desktop.
Save Yonaba/1054001 to your computer and use it in GitHub Desktop.
How To Compute Fraction
-- A function that return a fraction computed from a floating number.
function int(arg)
local e,d = math.modf(arg)
return e
end
function dec2fr(decimal,acc)
local acc = acc
if not acc then acc = 1E-4 end
local sign,z,predenum,sc,_,num,denum
if (decimal<0) then sign = -1 else sign = 1 end
decimal=math.abs(decimal)
if decimal == int(decimal) then
num = decimal*sign
denum = 1
end
if decimal < 1E-19 then
num = sign
denum = 9999999999999999999;
end
if decimal > 1E+19 then
num = 9999999999999999999*sign
denum = 1
end
z = decimal
predenum = 0
denum= 1
repeat
z = 1/(z-int(z))
sc = denum
denum = denum*int(z)+predenum
predenum = sc
num = int(decimal*denum)
until (math.abs(decimal-(num/denum))<acc) or (z==int(z))
num = sign*num
return num,denum
end
print(dec2fr(math.pi,1E10))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment