ValueError: math domain error, keeps popping up

2020-05-03 17:03发布

问题:

I keep getting this message from time to time. i tried all variations, changing the way i use the sqrt, doing it step by step..etc But still this error keeps popping up. It might be a rookie mistake which i am not noticing since i am new to python and ubuntu. This is my source code:-(a very simple program)

#To find the area of a triangle
a=input("Input the side 'a' of a triangle ")
b=input("Input the side 'b' of a trianlge ")
c=input("Input the side 'c' of a triangle ")
from math import *
s=(a+b+c)/2
sq=(s*(s-a)*(s-b)*(s-c))
area=(sqrt(sq)) 
perimeter=2*(a+b)
print "Area = ", area
print "perimeter=", perimeter

and this is the error i keep getting

Traceback (most recent call last):

   line 8, in <module>

    area=(sqrt(sq))

ValueError: math domain error

回答1:

As others have pointed out, your calculation for area using Heron's formula will involve the square root of a negative number if the three "sides" do not actually form a triangle. One answer showed how to handle that with exception handling. However, that does not catch the case where the three "sides" form a degenerate triangle, one with area zero and thus is not a traditional triangle. An example of that would be a=1, b=2, c=3. The exception also waits until you try the calculation to find the problem. Another approach is to check the values before the calculations, which will find the problem immediately and allows you to decide whether or not to accept a degenerate triangle. Here is one way to check:

a=input("Input the side 'a' of a triangle ")
b=input("Input the side 'b' of a triangle ")
c=input("Input the side 'c' of a triangle ")
if a + b <= c or b + c <= a or c + a <= b:
    print('Those values do not form a triangle.')
else:
    # calculate

Here is another check, with only two inequalities rather than the traditional three:

if min(a,b,c) <= 0 or sum(a,b,c) <= 2*max(a,b,c):
    print('Those values do not form a triangle.')
else:
    # calculate

If you want to allow degenerate triangles, remove the equal signs in the checks.



回答2:

If a,b,c doesn't form a triangle, sq will come out to be -ve. Check if s*(s-a)*(s-b)*(s-c) is positive because sqrt(-ve number) is a complex number.

To resolve this issue, you can use exception handling.

try:
  a=input("Input the side 'a' of a triangle ")
  b=input("Input the side 'b' of a trianlge ")
  c=input("Input the side 'c' of a triangle ")
  from math import *
  s=(a+b+c)/2
  sq=(s*(s-a)*(s-b)*(s-c))
  area=(sqrt(sq)) 
  perimeter=2*(a+b)
  print "Area = ", area
  print "perimeter=", perimeter
except ValueError:
  print "Invalid sides of a triangle"


标签: python math