ValueError:数学域错误,不断弹出 [英] ValueError: math domain error, keeps popping up

查看:94
本文介绍了ValueError:数学域错误,不断弹出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直不时收到此消息. 我尝试了所有变体,更改了我使用sqrt的方式,逐步进行了操作..etc 但是,此错误仍然不断弹出. 这可能是一个菜鸟错误,因为我是python和ubuntu的新手,所以我没有注意到. 这是我的源代码:-(一个非常简单的程序)

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

这是我不断得到的错误

Traceback (most recent call last):

   line 8, in <module>

    area=(sqrt(sq))

ValueError: math domain error

推荐答案

正如其他人所指出的那样,如果三个边"实际上没有形成一个三角形.一个答案显示了如何使用异常处理来处理该问题.但是,这并不能解决三个边"形成一个退化三角形的情况,该三角形的面积为零,因此不是传统的三角形.例如a=1, b=2, c=3.异常也将一直等到您尝试计算以发现问题为止.另一种方法是在计算之前检查值,这将立即发现问题,并使您可以决定是否接受退化的三角形.这是一种检查方法:

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.

这篇关于ValueError:数学域错误,不断弹出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆