Advertisement
Nothy

Quadratic Equation Solver (Lua)

Feb 28th, 2018
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.26 KB | None | 0 0
  1. -- Quadratic equation solver
  2. -- (C) Linus Ramneborg 2018
  3. -- All rights reserved. No redistribution allowed.
  4.  
  5. -- Description:
  6. -- Function used to solve for x1, x2 with numbers from a
  7. -- quadtratic equation, a so-called PQ formula.
  8. -- p represents p in px + q = 0, q represents q in that formula. You get it.
  9. -- The 'swap' variable is there so you can swap from + to - when calculating.
  10. -- https://en.wikipedia.org/wiki/Quadratic_equation
  11.  
  12. function pq(p,q, swap)
  13.   if p < 0 then error("bad argument #1, negative number not possible") end
  14.   if type(q) == "number" and q < 0 then error("bad argument #2, negative number not possible") end
  15.   if not swap then swap = false end
  16.  
  17.   local x1, x2 = 0
  18.   -- Calculate x1, x2 using x^2 + px + q = 0 solution
  19.   if not swap then
  20.     -- Check if q is a variable present
  21.     if q then
  22.       x1 = -(p/2) + (((p/2)^2)+q)^0.5
  23.  
  24.       x2 = -(p/2) - (((p/2)^2)+q)^0.5
  25.     else
  26.       x1 = -(p/2) + (((p/2)^2))^0.5
  27.  
  28.       x2 = -(p/2) - (((p/2)^2))^0.5
  29.     end
  30.   else
  31.     -- Check if q is a variable present
  32.     if q then
  33.       x1 = -(p/2) + (((p/2)^2)-q)^0.5
  34.  
  35.       x2 = -(p/2) - (((p/2)^2)-q)^0.5
  36.     else
  37.       x1 = -(p/2) + (((p/2)^2))^0.5
  38.  
  39.       x2 = -(p/2) - (((p/2)^2))^0.5
  40.     end
  41.  
  42.   end
  43.  
  44.   return x1, x2
  45.  
  46. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement