Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Quadratic equation solver
- -- (C) Linus Ramneborg 2018
- -- All rights reserved. No redistribution allowed.
- -- Description:
- -- Function used to solve for x1, x2 with numbers from a
- -- quadtratic equation, a so-called PQ formula.
- -- p represents p in px + q = 0, q represents q in that formula. You get it.
- -- The 'swap' variable is there so you can swap from + to - when calculating.
- -- https://en.wikipedia.org/wiki/Quadratic_equation
- function pq(p,q, swap)
- if p < 0 then error("bad argument #1, negative number not possible") end
- if type(q) == "number" and q < 0 then error("bad argument #2, negative number not possible") end
- if not swap then swap = false end
- local x1, x2 = 0
- -- Calculate x1, x2 using x^2 + px + q = 0 solution
- if not swap then
- -- Check if q is a variable present
- if q then
- x1 = -(p/2) + (((p/2)^2)+q)^0.5
- x2 = -(p/2) - (((p/2)^2)+q)^0.5
- else
- x1 = -(p/2) + (((p/2)^2))^0.5
- x2 = -(p/2) - (((p/2)^2))^0.5
- end
- else
- -- Check if q is a variable present
- if q then
- x1 = -(p/2) + (((p/2)^2)-q)^0.5
- x2 = -(p/2) - (((p/2)^2)-q)^0.5
- else
- x1 = -(p/2) + (((p/2)^2))^0.5
- x2 = -(p/2) - (((p/2)^2))^0.5
- end
- end
- return x1, x2
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement