【问题标题】:How to fix 'ValueError: math domain error' in python?如何修复 python 中的“ValueError:数学域错误”?
【发布时间】:2019-10-12 07:03:13
【问题描述】:

我正在尝试编写一个计算公式 y=√x*x + 3*x - 500 的程序, 区间为 [x1;x2] 和 f.e x1=15, x2=25。

我尝试使用异常处理,但没有帮助。 我现在尝试使用的代码给了我:ValueError:数学域错误

import math

x1 = int(input("Enter first number:"))
x2 = int(input("Enter second number:"))
print(" x", "   y")
for x in range(x1, x2):
    formula = math.sqrt(x * x + 3 * x - 500)
    if formula < 0:
        print("square root cant be negative")
    print(x, round(formula, 2))

输出应如下所示:

x   y
15 ***
16 ***
17 ***
18 ***
19 ***
20 ***
21 2.00
22 7.07
23 9.90
24 12.17
25 14.14

【问题讨论】:

  • 如果您愿意,也可以使用 x**.5 代替 math.sqrt(x)。它将 x 提高到 0.5(一半)的幂。

标签: python math error-handling valueerror sqrt


【解决方案1】:

平方根的参数不能是负数。在这里使用异常处理完全没问题,见下文:

游乐场:https://ideone.com/vMcewP

import math


x1 = int(input("Enter first number:\n"))
x2 = int(input("Enter second number:\n"))

print(" x\ty")
for x in range(x1, x2 + 1):
    try:
        formula = math.sqrt(x**2 + 3*x - 500)
        print("%d\t%.2f" % (x, formula))
    except ValueError:  # Square root of a negative number.
        print("%d\txxx" % x)


资源:

【讨论】:

    【解决方案2】:

    你必须检查表达式是否为&lt; 0在你取平方根之前。否则,您会采用负数的 sqrt,这会给您带来域错误。

    【讨论】:

    • 只需将 sqrt 向下移动到
    【解决方案3】:
    import math
    x1 = int(input("Enter first number:"))
    x2 = int(input("Enter second number:"))
    print(" x", "   y")
    for x in range(x1, x2+1):
        formula = x * x + 3 * x - 500
        if formula < 0:
            print (x, "***")
        else:
            formula = math.sqrt(formula)
            print(x, round(formula, 2))
    

    【讨论】:

      【解决方案4】:

      您应该尝试修改您的代码,如下所示。在执行sqrt之前计算表达式值

      print(" x", " y")
      for x in range(x1, x2):
          expres = x * x + 3 * x - 500
          if expres >= 0:
              formula = math.sqrt(expres)
              print(x, round(formula, 2))
          else:
              print(x, "***")
      
      #  x  y
      # 15 ***
      # 16 ***
      # 17 ***
      # 18 ***
      # 19 ***
      # 20 ***
      # 21 2.0
      # 22 7.07
      # 23 9.9
      # 24 12.17  
      # 25 14.14
      

      【讨论】:

        猜你喜欢
        • 2020-05-06
        • 2021-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多