平方根域误差

2024-05-19 00:02:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从我正在学习的书中复制一个代码。这个程序应该找到一个二次函数的平方根,但是一旦我在空闲状态下运行这个模块,我就会得到一个错误。你知道吗

#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值变为负值吗?你知道吗


Tags: ofthetoismain错误functionmath
1条回答
网友
1楼 · 发布于 2024-05-19 00:02:17

每当b * b - 4 * a * c是一个负数时,math.sqrt(b * b - 4 * a * c)就会产生一个ValueError。你知道吗

在前面检查,或者使用^{}模块中的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 )
.
.

相关问题 更多 >

    热门问题