python - 返回错误的正数#

1 投票
4 回答
1118 浏览
提问于 2025-04-16 10:01

我想做的是写一个二次方程的解算器,但当正确的解应该是 -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 个回答

1

top1top2 的符号是错的,具体可以参考这个链接:http://en.wikipedia.org/wiki/Quadratic_equation

2

二次方程的解是

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

但是你写的代码是

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

所以这就是你出现符号错误的原因。

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]

撰写回答