Advertisement
Bolodefchoco_LUAXML

[Math] math.toFraction

Sep 18th, 2016
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.17 KB | None | 0 0
  1. --Creator: Bolodefchoco
  2. --Made in: 18/09/2016
  3. --Last update: 18/09/2016
  4. --[[ Notes:
  5.     Does:
  6.         Retorna a fração reduzida de um número decimal (0.5 = 1/2)
  7.     Args:
  8.         x --> O número (Exemplo: 0.5)
  9.         reduce --> Se for true, ele irá reduzir (Exemplo: 13.3333 virará 13.33)
  10. ]]--
  11.  
  12. local cfact = function(x)
  13.     local num,den = x:match("(%d+)/(%d+)")
  14.     num,den = tonumber(num),tonumber(den)
  15.     while den ~= 0 do
  16.         local t = den
  17.         den = num%den
  18.         num = t
  19.     end
  20.     return num
  21. end
  22.  
  23. local isInteger = function(x)
  24.     return math.floor(x) - x == 0
  25. end
  26.  
  27. local simplify = function(x)
  28.     local num,den = x:match("(%d+)/(%d+)")
  29.     local f = cfact(x)
  30.     local n,d = num/f,den/f
  31.     if isInteger(n/d) then
  32.         return n/d
  33.     else
  34.         return n.."/"..d
  35.     end
  36. end
  37.  
  38. math.reduceDec = function(x,n)
  39.     local d = n and "1"..("0"):rep(n) or 100
  40.     return math.floor(x*d)/d
  41. end
  42.  
  43. math.toFraction = function(x,reduce)
  44.     if reduce then
  45.         x = math.reduceDec(x,1)
  46.     end
  47.     local int,dec = math.modf(x)
  48.     if dec == 0 then
  49.         return x
  50.     else
  51.         local numb,frac = tostring(x):match("(%d+)%.(%d+)")
  52.         local fracDen = "1" .. ("0"):rep(#frac)
  53.         local result = numb..frac.."/"..fracDen
  54.         return simplify(result)
  55.     end
  56. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement