What causes the problem?
from math import sqrt
print "a : "
a = float(raw_input())
print "b : "
b = float(raw_input())
print "c : "
c = float(raw_input())
d = (a + b + c)/2
s = sqrt(d*(d-a)*(d-b)*(d-c))
print "a+b+c =", a, b, c
print "Distr. =", d*2, "Area =", s
Error:
Traceback (most recent call last):
File "C:/Python27/fájlok/háromszög terület2.py", line 11, in <module>
s = sqrt(d*(d-a)*(d-b)*(d-c))
ValueError: math domain error
The ValueError: math domain error is raised when you perform a mathematical function on a negative or zero number which cannot be computed. To solve this error, make sure you are using a valid number for the mathematical function you are using.
Domain errors occur when the parameters to the functions are invalid, such as a negative number as a parameter to sqrt (the square root function).
A domain error occurs if an input argument is outside the domain over which the mathematical function is defined. A pole error (also known as a singularity or infinitary) occurs if the mathematical function has an exact infinite result as the finite input argument(s) are approached in the limit.
Python's math module, in the standard library, can help you work on math-related problems in code. It contains many useful functions, such as remainder() and factorial() . It also includes the Python square root function, sqrt() .
The problem is that the Heron's formula holds good only when the sum of the two numbers are greater than the third. You need to check that explicitly.
A better way as you are using a code to do that is by using Exception handling
try:
s = sqrt(d*(d-a)*(d-b)*(d-c))
print "a+b+c =", a, b, c
print "Distr. =", d*2, "Area =", s
except ValueError:
print "Please enter 3 valid sides"
If you want to do it without try
block you can do it as
delta = (d*(d-a)*(d-b)*(d-c))
if delta>0:
s = sqrt(delta)
print "a+b+c =", a, b, c
print "Distr. =", d*2, "Area =", s
else:
print "Please enter 3 valid sides"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With