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

╄→гoц情女王★ 提交于 2021-02-05 08:53:07

问题


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.

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

The output should look like this:

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

回答1:


The argument of square root mustn't be negative. It's perfectly fine to use exception handling here, see below:

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


Resources:

  • wiki.python.org: Handling Exceptions



回答2:


You have to check whether the expression is < 0 before you take the square root. Otherwise you take the sqrt of a negative number which gives you a domain error.




回答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:


You should try to modify your code as shown below. Compute the expression value before performing 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://stackoverflow.com/questions/56313605/how-to-fix-valueerror-math-domain-error-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!