python - returns incorrect positive #

Posted by tekknolagi on Stack Overflow See other posts from Stack Overflow or by tekknolagi
Published on 2011-01-15T18:29:27Z Indexed on 2011/01/15 18:54 UTC
Read the original article Hit count: 186

Filed under:
|
|
|
|

what i'm trying to do is write a quadratic equation solver but when the solution should be -1, as in quadratic(2, 4, 2) it returns 1

what am i doing wrong?

#!/usr/bin/python
import math
def quadratic(a, b, c):
        #a = raw_input("What\'s your `a` value?\t")
        #b = raw_input("What\'s your `b` value?\t")
        #c = raw_input("What\'s your `c` value?\t")
        a, b, c = float(a), float(b), float(c)
        disc = (b*b)-(4*a*c)
        print "Discriminant is:\n" + str(disc)
        if disc >= 0:
                root = math.sqrt(disc)
                top1 = b + root
                top2 = b - root
                sol1 = top1/(2*a)
                sol2 = top2/(2*a)
                if sol1 != sol2:
                        print "Solution 1:\n" + str(sol1) + "\nSolution 2:\n" + str(sol2)
                if sol1 == sol2:
                        print "One solution:\n" + str(sol1)
        else:
                print "No solution!"

EDIT: it returns the following...

>>> import mathmodules
>>> mathmodules.quadratic(2, 4, 2)
Discriminant is:
0.0
One solution:
1.0

© Stack Overflow or respective owner

Related posts about python

Related posts about math