ValueError:数学域错误-二次方程式(Python) [英] ValueError: math domain error - Quadratic Equation (Python)
问题描述
我对python编程和本网站非常陌生.我目前正在处理一个问题,似乎无法理解该错误.
I'm very new to python programming and to this site. I'm currently working on a problem and can't seem to understand the error.
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)
我在运行它后得到了它:
I get this after i run it:
x9 = (-B5 + math.sqrt(B5**2 - 4*A5*C5))/(2*A5)
ValueError: math domain error
我在纸上做了问题,并得到了答案……
I did the problem on paper and got an answer for both...
推荐答案
如果您得到了答案,则它一定是一个复数(Python默认不包含).查看math.sqrt(B5**2 - 4*A5*C5)
行.
If you got an answer, it must have been a complex number (which are not included by default in Python). Look at the line 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
,因为那样做(这需要在程序开始时import
ing cmath
).
The function math.sqrt
doesn't find complex roots. You should use cmath.sqrt
instead, as that does (this will require import
ing cmath
at the start of your program).
使用cmath
,我得到以下结果:
Using cmath
, I get this result:
Problem #5
Root 1: 1.1401754250991378j
Root 2: 1.1401754250991378j
(其中j
是-1的平方根).
(where j
is the square root of -1).
这篇关于ValueError:数学域错误-二次方程式(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!