开发者

python - returns incorrect positive #

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:
                p开发者_运维知识库rint "No solution!"

EDIT: it returns the following...

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


Unless the formula has changed since I went to school (one can never be too sure), it's (-b +- sqrt(b^2-4ac)) / 2a, you have b in your code.

[edit] May I suggest a refactor?

def quadratic(a, b, c):
    discriminant = b**2 - 4*a*c
    if discriminant < 0:
      return []
    elif discriminant == 0:
      return [-b / (2*a)]
    else:
      root = math.sqrt(discriminant)
      return [(-b + root) / (2*a), (-b - root) / (2*a)]

print quadratic(2, 3, 2) # []
print quadratic(2, 4, 2) # [-1]                    
print quadratic(2, 5, 2) # [-0.5, -2.0]


The solution to the quadratic is

x = (-b +/- sqrt(b^2 - 4ac))/2a

but what you have coded up is

x = (b +/- sqrt(b^2 - 4ac))/2a

So that's why you get the sign error.


The signs of top1 and top2 are wrong, see http://en.wikipedia.org/wiki/Quadratic_equation


top1 = b + root
top2 = b - root

Should be:

top1 = -b + root
top2 = -b - root
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜