Advertisement
imring

[LUA] Frac

Mar 4th, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.96 KB | None | 0 0
  1. local function to_frac(num)
  2.   local int, fract = math.modf(num)
  3.   if fract == 0 then
  4.     return int, 1, 0
  5.   end
  6.   local W = math.floor(fract)
  7.   local F = fract - W
  8.   local pn, n, N = 0, 1
  9.   local pd, d, D = 1, 0
  10.   local x, err, q, Q
  11.   repeat
  12.     x = x and 1 / (x - q) or F
  13.     q, Q = math.floor(x), math.floor(x + 0.5)
  14.     pn, n, N = n, q*n + pn, Q*n + pn
  15.     pd, d, D = d, q*d + pd, Q*d + pd
  16.     err = F - N/D
  17.   until math.abs(err) < 1e-15
  18.   return N + D*W, D, int + err
  19. end
  20.  
  21. if not _ARGS then return '!!fract [numb] (numb2)' end
  22. local n, n2 = string:match(_ARGS, '(%S+)%s*(.*)')
  23. n = tonumber(n)
  24. if not n then return 'Send numb.' end
  25. n2 = tonumber(n2)
  26. if n2 then
  27.     local numb, dec, int = to_frac(n / n2)
  28.     return string.format('%g/%g = %d/%d + %g = %d/%d', n, n2, numb, dec, int, numb + int * dec, dec)
  29. else
  30.     local numb, dec, int = to_frac(n)
  31.     return string.format('%g = %d/%d + %g = %d/%d', n, numb, dec, int, numb + int * dec, dec)
  32. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement