Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python math domain error - sqrt

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
like image 891
szzso24 Avatar asked Mar 31 '15 18:03

szzso24


People also ask

How do I fix the math domain error in Python?

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.

What is sqrt domain error?

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

What is the math domain error?

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.

Is sqrt () in the Python math library?

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


1 Answers

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"
like image 200
Bhargav Rao Avatar answered Oct 04 '22 11:10

Bhargav Rao