3

So I made a python code that solves for x using the quadratic formula. Everything works out in the end except for the signs. For instance, if you want to factor x^2 + 10x + 25, my code outputs -5, -5 when the answer should be 5, 5.

def quadratic_formula():
    a = int(input("a = "))
    b = int(input("b = "))
    c = int(input("c = "))
    bsq = b * b
    fourac = 4 * a * c
    sqrt = (bsq - fourac) ** (.5)
    oppb = -b
    numerator_add = (oppb) + (sqrt)
    numerator_sub = (oppb) - (sqrt)
    twoa = 2 * a
    addition_answer = (numerator_add) / (twoa)
    subtraction_answer = (numerator_sub) / (twoa)
    print(addition_answer)
    print(subtraction_answer)
Gabbi
  • 33
  • 2
  • 1
    The answer is -5, -5 replace x by the answer and see what it comes to (-5)^2 + 10(-5) + 25 = 25 - 50 + 25 = 0 – mmmmmm Sep 05 '16 at 22:42
  • Yes but it's strange because when you distribute that answer (x-5)(x-5) you get x^2 - 10x + 25 instead of x^2 + 10x + 25 – Gabbi Sep 05 '16 at 22:44
  • 1
    The correct factored version is (x + 5)^2. There are two roots at -5 – OneCricketeer Sep 05 '16 at 22:45
  • @cricket_007 exactly, that's where I'm getting confused. How do I get my outputs to be 5 and 5 instead of -5 and -5 – Gabbi Sep 05 '16 at 22:47
  • Set the value of `b` to be `-10` for (-5, - 5), otherwise `10` for (5,5) – OneCricketeer Sep 05 '16 at 22:48
  • but the value of b is 10 in this example, not -10. My code changed 10 to -10 in oppb which takes the opposite of b. – Gabbi Sep 05 '16 at 22:50

1 Answers1

5

Your solution is fine, let's prove it using sympy:

>>> (x**2+10*x+25).subs(x,-5)
0

As you can see, -5 is one of the roots while 5

>>> (x**2+10*x+25).subs(x,5)
100

is not, now... if you expand your 2 roots [-5,-5] like:

>>> ((x+5)*(x+5)).expand()
x**2 + 10*x + 25

You can see like the result matches.

In fact, you can also confirm the roots are correct displaying the quadratic equation:

enter image description here

I'd strongly recommend you review the concept of The Quadratic Formula and when it's clear just come back to the coding

BPL
  • 9,632
  • 9
  • 59
  • 117
  • OH right. I completely forgot that the -5 goes in for x not (x + __ <–here). thanks – Gabbi Sep 05 '16 at 22:55
  • @Gabbi You're welcome, it's very useful and fun to use coding to check your maths are correct and reinforce your learning. But make sure all of this it's first clear with pen & paper ;-) – BPL Sep 05 '16 at 23:02