Jump to content




Problem with quadratic equations


  • You cannot reply to this topic
6 replies to this topic

#1 Klausar

  • Members
  • 110 posts

Posted 29 September 2012 - 07: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.

#2 robhol

  • Members
  • 182 posts

Posted 29 September 2012 - 08: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

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


#3 Klausar

  • Members
  • 110 posts

Posted 29 September 2012 - 08: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

#4 robhol

  • Members
  • 182 posts

Posted 29 September 2012 - 08: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.

#5 Klausar

  • Members
  • 110 posts

Posted 29 September 2012 - 09:08 AM

I never used a formula with abc what is a what is b and what is c here:

0=x² + 5x + 9 ?

#6 robhol

  • Members
  • 182 posts

Posted 29 September 2012 - 09:15 AM

a=1, b=5, c=9. They're just the coefficients for the individual "degrees" of x.

#7 Klausar

  • Members
  • 110 posts

Posted 29 September 2012 - 09: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.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users