我写了一个名为analyze_the_shape
的函数,它取得了一个2D顶点列表,使得该列表按照二维欧几里德空间中顶点的顺时针遍历顺序排列。为什么我会得到ValueError:数学域错误?
我在口译员称它为[(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
'abs(angle-90.0)<0.001'和'abs(cos_angle + 1)<0.001'并不意味着相同。如果'angle = 90','cos_angle = 0'。如果'cos_angle = -1','angle = 180'。 –
好赶上!我认为在OP设置“cos_angle”时出现错误 - 我在回答中指出了这一点。 –
“Python存储'cos_angle'的方式并不完美”。这应该是“在计算机上表示浮点数的方式并不完美,因此计算错误是不可避免的”。 Python与此完全无关。 – Bakuriu