继续得到数学域错误

时间:2015-02-08 00:48:42

标签: python math

import math

print ("f(x) = ax2 + bx + c")

# #Get a, b and c from user

aval = float(input("Please Enter (a) value: "))
bval = float(input("Please Enter (b) value: "))
cval = float(input("Please Enter (c) calue: "))

# #Find roots
# THIS IS WERE IT GOES WRONG

root1 = (-(bval) + math.sqrt(bval**2 - 4*aval*cval))
root2 = (-(bval) - math.sqrt(bval**2 - 4*aval*cval))

#Check discriminant

discrim = float((bval**2)-(4*aval*cval))

if float(discrim > 0):
    print ("Roots at: ",roo1,root2)

elif float(discrim == 0):
    print ("Only one real root: ", root1, root2)

else:
    print ("No real Roots.")

2 个答案:

答案 0 :(得分:0)

您正在计算sqrt(bval**2 - 4*aval*cval),其中parens中的所有参数都是用户提供的。如果你输入一些让论证为负的东西,你就会得到错误。

答案 1 :(得分:0)

正如其他人所说,你应该只使用适当的值来呼叫sqrt()

做得更好

...

#Check discriminant

discrim = float((bval**2)-(4*aval*cval))

if float(discrim >= 0):
    # now it is ok to calculate the roots...
    root1 = - bval + math.sqrt(discrim)
    root2 = - bval - math.sqrt(discrim)

    if float(discrim > 0):
        print ("Roots at:", root1, root2)
    else:
        print ("Only one real root:", root1, root2)
else:
    print ("No real roots.")

这样我们就可以确保我们可以拨打sqrt