如何在python中修复'ValueError:Math domain error'? [英] How to fix 'ValueError: math domain error' in python?
本文介绍了如何在python中修复'ValueError:Math domain error'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个计算公式y =√x* x + 3 * x-500的程序,间隔为[x1; x2],且f1 = 15,x2 = 25.
I am trying to write a program which calculates formula y=√x*x + 3*x - 500, Interval is [x1;x2] and f.e x1=15, x2=25.
我尝试使用异常处理,但没有帮助.现在我尝试使用的代码给了我:ValueError:数学域错误
I tried to use Exception Handling but it didn't help. And the code I try to use now gives me: 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
推荐答案
平方根的参数不能为负.在这里使用异常处理完全可以,请参见下文:
The argument of square root mustn't be negative. It's perfectly fine to use exception handling here, see below:
游乐场: 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)
资源:
这篇关于如何在python中修复'ValueError:Math domain error'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文