我写了一个名为
我在解释器中调用它,并给出
analyze_the_shape
的函数,它接受一个顺时针遍历2D欧几里得空间中顶点的列表作为输入。我在解释器中调用它,并给出
[(0, 0), (0, 4.0), (4.0, 4.0), (4.0, 0)]
作为输入,但我得到了ValueError: math domain error
的错误信息。我期望看到return ["SQUARE", 4.0]
。我该怎么办?import math
def analyze_the_shape(liste):
if len(liste) == 2 :
d = ( (liste[1][0] - liste[0][0])**2 + (liste[1][1] - liste[0][1])**2 )**(0.5)
return ["LINESEGMENT", d ]
if len(liste) == 4 :
d1 = abs(( (liste[1][0] - liste[0][0])**2 + (liste[1][1] - liste[0][1])**2 )**(0.5))
d2 = abs(( (liste[2][0] - liste[1][0])**2 + (liste[2][1] - liste[1][1])**2 )**(0.5))
d3 = abs(( (liste[3][0] - liste[2][0])**2 + (liste[3][1] - liste[2][1])**2 )**(0.5))
d4 = abs(( (liste[0][0] - liste[3][0])**2 + (liste[0][1] - liste[3][1])**2 )**(0.5))
hypo = abs(( (liste[2][1] - liste[0][1])**2 + (liste[2][0] - liste[0][0])**2 )**(0.5))
cos_angle = float((hypo**2 - (d3)**2 + (d4)**2) / ((-2.0)*(d4)*(d3)))
angle = math.degrees(math.acos(cos_angle))
if d1 == d2 == d3 == d4 and abs(angle - 90.0) < 0.001 :
return ["SQUARE", d1]
我收到的错误信息如下:
>>> import a
>>> a.analyze_the_shape([(0, 0), (0, 4.0), (4.0, 4.0), (4.0, 0)])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "a.py", line 15, in analyze_the_shape
ValueError: math domain error
cos_angle
时有一个错误——我在我的答案中指出了这一点。 - Sam Mussmanncos_angle
的方式并不完美。这意味着计算机上浮点数的表示并不完美,因此计算误差是不可避免的。Python与此毫无关系。 - Bakuriu