【问题标题】:ValueError: math domain error in a second grade equation [duplicate]ValueError:二年级方程式中的数学域错误[重复]
【发布时间】:2017-04-13 22:29:54
【问题描述】:

谁能告诉我为什么会出现这个错误?

Traceback (most recent call last):
  File "file.py", line 14, in <module>
    p2 = math.sqrt(b*b -4*a*c)
ValueError: math domain error

我是一个新手编码,所以需要一些帮助:)

我的代码如下所示:

# -*- coding: utf-8 -*-
a = input("¿Qué valor es a?")
while(str(a).isdigit() != True):
  a = input("Porfavor, introduce un número para a, no un texto")
b = input("¿Qué valor es b?")
while(str(b).isdigit() != True):
  b = input("Porfavor, introduce un número para b, no un texto")
c = input("¿Qué valor es c?")
while(str(c).isdigit() != True):
  c = input("Porfavor, introduce un número para c, no un texto")

import math
p1 = b * -1
p2 = math.sqrt(b*b -4*a*c)
p3 = 2*a
s1 = (p1+p2)/p3
s2 = (p1-p2)/p3
print("Soluciones :", s1, " y ", s2)

【问题讨论】:

  • math.sqrt 不处理负值...
  • 您确定执行时输入的参数 a、b 和 c 是有效解吗?如果4*a*c &gt; b*b 二次方程没有解。您应该添加IF(4*a*c&gt;b*b): print("No solutions") else: ...的支票
  • @trashy 确定有解决方案,如果您的域是复数。
  • @juanpa.arrivillaga 在整篇文章中都没有提到使用复数。当然,您可以将 cmath 用于复杂的 sqrt 函数,然后找到两个虚根。但我不认为这就是问题所在。 (或者对正常的sqrt使用负值并手动添加i和-i)
  • @trashy 我唯一的一点是需要更好地说明问题。

标签: python


【解决方案1】:

您必须使 math.sqrt 不接受负值。所以如果 b*b-4*a*c 是一个负数,那么你会得到数学域错误。解决此问题的一种方法是使用 if 语句预先检查 sqrt 操作中的值是否为负值。

【讨论】:

    【解决方案2】:

    我假设您不是在寻找虚根 如果你是你应该看看cmath

    您应该将该块更改为

    try:
        p1 = b * -1
        math.sqrt(b**2 - 4*a*c)
        p3 = 2*a
        s1 = (p1+p2)/p3
        s2 = (p1-p2)/p3
        print("Soluciones :", s1, " y ", s2)
    except ValueError:
        print("No real solution")
    

    这称为异常处理,它是处理此类情况的完美工具。唯一一次它会进入 except 语句是如果 math.sqrt() 被赋予负数。在这种情况下,根是虚构的,所以 print("No real Solution") 或任何你想要的错误信息!

    【讨论】:

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