How to fix 'ValueError: math domain error' in python?

How to fix 'ValueError: math domain error' in python?

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

我尝试使用异常处理,但没有用。 我现在尝试使用的代码给了我:ValueError: math domain error

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

在 求平方根之前,您必须检查表达式是否 < 0 。否则你会取一个负数的平方,这会给你一个域错误。

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))

您应该尝试修改您的代码,如下所示。在执行 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

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

游乐场: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)


资源: