【问题标题】:ValueError: math domain error when using math.sqrt() [duplicate]ValueError:使用 math.sqrt() 时出现数学域错误 [重复]
【发布时间】:2016-10-29 19:54:47
【问题描述】:

我正在尝试编写一个程序来检查 triesmax_tries 范围内的 Herone Triangle,但 math.sqrt() 让我头疼

这是我的代码

import math
max_tries = 10000
tries = 1
half_perimeter = ((tries * 3) + 3) / 2

for num in range(tries,max_try,1):
    area = math.sqrt(half_perimeter * (half_perimeter - tries) * (half_perimeter - tries - 1) * (half_perimeter - tries - 2))
    if isinstance(area, int ) == True:
        print (tries)
        tries = tries + 1
    else :
        tries = tries + 1

每当我运行时,我都会从 python 获得ValueError: math domain error。我的代码有什么问题?返回的整个错误是

Traceback (most recent call last):
File "C:\Users\phong\AppData\Local\Programs\Python\Python35\Herone Triangle.py", line 9, in <module>
area = math.sqrt(half_perimeter * (half_perimeter - tries) * (half_perimeter - tries - 1) * (half_perimeter - tries - 2))
ValueError: math domain error

我还是个脚本小子,刚接触 Python。谢谢大家

【问题讨论】:

标签: python math


【解决方案1】:

由于half_perimeter 在循环外被初始化,它的值总是((1 * 3) + 3) / 2 = (3 + 3) / 2 = 6 / 2 = 3。然后,在循环内部,某些因素会在某些情况下变为负数,而在其中的一个子集中,奇数个因素将变为负数。这导致sqrt 的整个参数变为负数,从而导致域错误,因为math.sqrt 仅在结果为真实时才有效。

【讨论】:

  • 这应该是主要错误。将half_perimeter 的评估放在循环中,至少Heron 公式是正确的。
【解决方案2】:

在我看来,您并不真正了解for 循环的工作方式。它执行它“内部”的所有代码,然后(在这种情况下)将一个添加到tries

因此,在每次迭代中,您将 2 添加到 tries - 首先在您的代码中,然后 for 循环 iteslf 执行此操作。

我还认为您需要在每次迭代时再次计算 half_perimeter - 否则它总是相同的并且您会遇到数学错误(负数的平方根)。

【讨论】:

    【解决方案3】:

    这个等式在某些时候给出负数 half_perimeter * (half_perimeter - Try) * (half_perimeter - Try - 1) * (half_perimeter - Try - 2) 因此 math.sqrt() 调用正在返回错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-23
      • 2017-01-04
      • 1970-01-01
      • 2016-08-08
      • 1970-01-01
      • 2021-11-10
      • 2019-10-12
      相关资源
      最近更新 更多