Bolodefchoco_LUAXML

[Math] math.bhaskara

Sep 18th, 2016
349
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.78 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 o bhaskara da equação
  7.     Args:
  8.         e --> A equação (xy²+xy+x)
  9. ]]--
  10.  
  11. local cfact = function(x)
  12.     local num,den = x:match("(%d+)/(%d+)")
  13.     num,den = tonumber(num),tonumber(den)
  14.     while den ~= 0 do
  15.         local t = den
  16.         den = num%den
  17.         num = t
  18.     end
  19.     return num
  20. end
  21.  
  22. local isInteger = function(x)
  23.     return math.floor(x) - x == 0
  24. end
  25.  
  26. local simplify = function(x)
  27.     local num,den = x:match("(%d+)/(%d+)")
  28.     local f = cfact(x)
  29.     local n,d = num/f,den/f
  30.     if isInteger(n/d) then
  31.         return n/d
  32.     else
  33.         return n.."/"..d
  34.     end
  35. end
  36.  
  37. math.reduceDec = function(x,n)
  38.     local d = n and "1"..("0"):rep(n) or 100
  39.     return math.floor(x*d)/d
  40. end
  41.  
  42. math.toFraction = function(x,reduce)
  43.     if reduce then
  44.         x = math.reduceDec(x,1)
  45.     end
  46.     local int,dec = math.modf(x)
  47.     if dec == 0 then
  48.         return x
  49.     else
  50.         local numb,frac = tostring(x):match("(%d+)%.(%d+)")
  51.         local fracDen = "1" .. ("0"):rep(#frac)
  52.         local result = numb..frac.."/"..fracDen
  53.         return simplify(result)
  54.     end
  55. end
  56.  
  57. local getDiv = function(d)
  58.     if type(d) == "string" then
  59.         local f,d = d:match("(%d+)/(%d+)")
  60.         return f/d
  61.     else
  62.         return d
  63.     end
  64. end
  65.  
  66. math.bhaskara = function(e)
  67.     e = e:gsub(" ","")
  68.     local a,x,b,c = e:match("(%p*%d+)(%a*)²*.*(%p%d+).*(%p%d+)")
  69.     a,b,c,x = tonumber(a),tonumber(b),tonumber(c),x or "x"
  70.     local delta = (b^2) - 4*a*c
  71.     delta = delta^.5
  72.     if delta < 0 or delta ~= delta then
  73.         return "Delta is negative"
  74.     else
  75.         local x1 = (-b + delta) / (2*a)
  76.         local x2 = (-b - delta) / (2*a)
  77.         x1,x2 = x1~=x1 and 0 or math.toFraction(x1,true),x2~=x2 and 0 or math.toFraction(x2,true)
  78.         local max = getDiv(x1) > getDiv(x2) and {x1,x2} or {x2,x1}
  79.         return x:upper() .. " = {"..max[1]..", "..max[2].."}"
  80.     end
  81. end
Advertisement
Add Comment
Please, Sign In to add comment