简体   繁体   English

ValueError:数学域错误 - 二次方程 (Python)

[英]ValueError: math domain error - Quadratic Equation (Python)

I'm very new to python programming and to this site.我对 python 编程和这个站点很陌生。 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...我在纸上解决了这个问题并得到了两个答案......

If you got an answer, it must have been a complex number (which are not included by default in Python).如果你得到了答案,它一定是一个复数(Python 中默认不包含)。 Look at the line math.sqrt(B5**2 - 4*A5*C5) .查看math.sqrt(B5**2 - 4*A5*C5)

This evaluates as so:这评估如下:

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

The function math.sqrt doesn't find complex roots.函数math.sqrt找不到复根。 You should use cmath.sqrt instead, as that does (this will require import ing cmath at the start of your program).您应该使用cmath.sqrt代替,就像那样(这将需要在程序开始时import cmath )。

Using cmath , I get this result:使用cmath ,我得到这个结果:

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

(where j is the square root of -1). (其中j是 -1 的平方根)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM