平方根的域错误

时间:2016-09-04 14:05:58

标签: python python-3.x

我正在尝试复制我正在学习的书中的代码。该程序应该找到二次函数的平方根,但是一旦我在IDLE中运行该模块,我就会收到错误。

#This is a program to find the square roots of a quadratic function.



import math

def main():

    print ("this is a program to find square roots of a quadratic function")
    print()
    a,b,c = eval(input("enter the value of the coefficients respectively"))

    discRoot = math.sqrt( b * b - 4 * a * c )

    root1 = ( - b + discRoot ) / 2 * a 
    root2 = ( - b - discRoot ) / 2 * a

    print ("The square roots of the equation are : ", root1, root2 )
    print()

main()

我收到以下错误:

Traceback (most recent call last):
File "/home/ubuntu/Desktop/untitled.py", line 21, in <module>
main()
File "/home/ubuntu/Desktop/untitled.py", line 13, in main
discRoot = math.sqrt( b * b - 4 * a * c )
ValueError: math domain error

我到底错在了什么?是因为discRoor值变成负值吗?

1 个答案:

答案 0 :(得分:1)

每次b * b - 4 * a * c为负数,math.sqrt(b * b - 4 * a * c)都会引发ValueError

要么检查之前,要么使用cmath模块中的sqrt来允许复杂的根源:

.
.
delta = b * b - 4 * a * c
if delta > 0:
     discRoot = math.sqrt(delta)
else:
    print("No solutions")
.
.

或允许复杂的根源:

import cmath

.
.
discRoot = cmath.sqrt( b * b - 4 * a * c )
.
.