gpt4 book ai didi

python - 值错误 : math domain error - Quadratic Equation (Python)

转载 作者:太空宇宙 更新时间:2023-11-03 11:28:38 31 4
gpt4 key购买 nike

我对 Python 编程和这个网站还很陌生。我目前正在处理一个问题,但似乎无法理解错误。

import math
# Problem number 5.
A5 = 5
B5 = 0
C5 = 6.5
# Root1
x9 = (-B5 + math.sqrt(B5**2 - 4*A5*C5))/(2*A5)
# Root2
x10 = (-B5 + math.sqrt(B5**2 - 4*A5*C5))/(2*A5)
# Print solution
print()
print('Problem #5')
print('Root 1: ',x9)
print('Root 2: ',x10)

运行后我得到了这个:

    x9 = (-B5 + math.sqrt(B5**2 - 4*A5*C5))/(2*A5)
ValueError: math domain error

我在纸上做了这个问题并得到了两个答案......

最佳答案

如果您得到答案,那一定是一个复数(默认情况下不包含在 Python 中)。查看行 math.sqrt(B5**2 - 4*A5*C5)

这样计算:

math.sqrt(B5**2 - 4*A5*C5)
math.sqrt(0**2 - 4*5*6.5)
math.sqrt(0 - 130)
math.sqrt(-130)

math.sqrt 函数不求复根。您应该像那样使用 cmath.sqrt(这需要在程序开始时使用 importing cmath)。

使用 cmath,我得到了这个结果:

Problem #5
Root 1: 1.1401754250991378j
Root 2: 1.1401754250991378j

(其中 j 是 -1 的平方根)。

关于python - 值错误 : math domain error - Quadratic Equation (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28232673/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com