This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Klausar's profile picture

Problem with quadratic equations

Started by Klausar, 29 September 2012 - 06:35 AM
Klausar #1
Posted 29 September 2012 - 08:35 AM
I want to make a calculator which can solve quadratic equaitons with a P and a Q value. But I'm pretty new to LUA eventhough I already made a calculator for +,-,/ and * :P/>/>. The formula looks like this:

x1,2 = -p/2 ± √(p/2)²-q

Could someone help me with that? I would be grateful.

± = plusminus btw.
robhol #2
Posted 29 September 2012 - 09:33 AM
Not sure what you mean by P and Q values. For any general quadratic eq of the form ax^2 + bx + c = 0, x = (-b +/- math.sqrt(math.pow(b,2)-4*a*c) )/(2 * a).
You'll have to basically copy-paste* the code to get both solutions, and might want to check if you're about to get a non-real answer, ie. sqrt-ing something negative. Otherwise, you'll get "nan".

*) Copy-pasting/duplicating code is usually not the best idea, but there's no huge reason not to in this particular case

My solution, but try on your own first;
Spoiler

function queq(a, b, c)
	local disc = math.sqrt(  math.pow(b,2) - 4 * a * c  );
	return (-b + disc) / (2 * a), (-b - disc) / (2 * a)
end

Another solution with minimal code duplication, just to see if it was worth the hassle
Spoiler

function queq2(a, b, c)
	local function f(x) return (-b + x) / (2 * a); end
	local disc = math.sqrt(  math.pow(b,2) - 4 * a * c  );
	return f(disc), f(-disc);
end
Klausar #3
Posted 29 September 2012 - 09:42 AM
Well in Germany we use P and Q so I'm not really used to your formula, for example:

x² + 5x + 9
P would be 5
Q would be 9
robhol #4
Posted 29 September 2012 - 09:55 AM
Mine's better ;P
You basically call b P and c Q, and you assume that a = 1 - ie my solution is more flexible.

An example:
(x-4)(x+5) = x^2 + x - 20
ax^2 + bx + c
a is 1, b is 1, c is -20.
Klausar #5
Posted 29 September 2012 - 10:08 AM
I never used a formula with abc what is a what is b and what is c here:

0=x² + 5x + 9 ?
robhol #6
Posted 29 September 2012 - 10:15 AM
a=1, b=5, c=9. They're just the coefficients for the individual "degrees" of x.
Klausar #7
Posted 29 September 2012 - 10:42 AM
Thanks, can you maybe also show me a code where it requests input etc.? I never worked with functions, sorry for my noobiness.