【问题标题】:ValueError: math domain error - Quadratic Equation (Python)ValueError:数学域错误 - 二次方程(Python)
【发布时间】:2015-01-30 09:21:07
【问题描述】:

我对 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

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

【问题讨论】:

  • 你是如何在纸上得到 0^2 - 4*5*6.5 = -130 的平方根的?因为这就是这里发生的事情,即math domain error。
  • ValueError: math domain error 的可能重复项
  • 嗯,我用了一个计算器,只对 -4(5)(6.5) 求平方,得到 11.40,然后除以 10,得到 1.14 作为答案。

标签: python math equation quadratic


【解决方案1】:

如果你得到答案,它一定是一个复数(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书,但我还没有看过cmath。无论如何,谢谢!
猜你喜欢
  • 1970-01-01
  • 2014-12-08
  • 1970-01-01
  • 1970-01-01
  • 2021-08-04
  • 1970-01-01
  • 2020-05-06
  • 1970-01-01
  • 2020-06-22
相关资源
最近更新 更多