Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

incorrect answers for quadratic equations

Tags:

python

I was wondering if anyone could tell me why my python code for solving quadratic equations isn't working. I have looked through it and haven't found any errors.

print("This program will solve quadratic equations for you")

print("It uses the system 'ax**2 + bx + c'")

print("a, b and c are all numbers with or without decimal \
points")

print("Firstly, what is the value of a?")

a = float(input("\n\nType in the coefficient of x squared"))

b = float(input("\n\nNow for b. Type in the coefficient of x"))

c = float(input("\n\nGreat. now what is the c value? The number alone?"))

print("The first value for x is " ,(-b+(((b**2)-(4*a* c))* * 0.5)/(2*a)))

print("\n\nThe second value for x is " ,(-b-(((b * * 2)-(4*a*c))** 0.5)/(2*a)))

When a=1 b=-4 and c=-3 I am expecting -1 and 4 but get 5.5 and 0.5

like image 469
Michael Dunwoody Avatar asked Jul 05 '15 16:07

Michael Dunwoody


1 Answers

Your trouble is in the part that tries to do the quadratic formula:

(-b+(((b**2)-(4*a* c))* * 0.5)/2*a)

The trouble is that * has the same precedence as / so you're dividing by 2 and then multiplying by a. Also your parentheses are off, so I reduced the unnecessary ones and moved the wrong ones. In short, -b wasn't being put together with the square root before the division. What you want is:

(-b+(b**2-4*a*c)**0.5)/(2*a)

P.S. For the sake of asking questions, it would be better to ask in the form of something like:

>>> a = 2
>>> b = 1
>>> c = 3
>>> (-b+(((b**2)-(4*a* c))* * 0.5)/2*a)
got blah, expected blam

Since the other printing and inputting is not to blame (which you should be able to work out fairly easily).

like image 107
CrazyCasta Avatar answered Sep 21 '22 09:09

CrazyCasta