python - 返回错误的正#

时间:2011-01-15 18:29:28

标签: python math module quadratic function

我要做的是写一个二次方程求解器但是当解决方案应该是-1时,就像在quadratic(2, 4, 2)中一样,它返回1

我做错了什么?

#!/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!"

编辑:它返回以下内容......

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

4 个答案:

答案 0 :(得分:12)

除非我上学后公式发生了变化(人们永远不能确定),所以(-b +- sqrt(b^2-4ac)) / 2a,你的代码中有b

[编辑]我可以建议一个重构吗?

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]

答案 1 :(得分:2)

二次方的解是

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

但你编码的是

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

这就是你收到签名错误的原因。

答案 2 :(得分:1)

top1top2的迹象有误,请参阅http://en.wikipedia.org/wiki/Quadratic_equation

答案 3 :(得分:0)

top1 = b + root
top2 = b - root

应该是:

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